I'm converting the xpath to Jsoup
below is my xpath (which is used in my selenium webdriver)
String number = driver.findElement(By.xpath("//span[#data-dojo-attach-point='subNumber']")).getText();
equivalent jsoup
String number = doc.select(" >span >data-dojo-attach-point=subNumber").text();
System.out.println(number);
While executing getting below error
Could not parse query 'data-dojo-attach-point=subNumber': unexpected token at '=subNumber'
HTML:
<div class="subHeaders">
<div class="subHeaderItem">
<h5 class="smallGray">Number</h5>
<span data-dojo-attach-point="subNumber">94607506</span>
</div>
</div>
can anyone help this.
This is the way you could retrieve that data with selectFirst(String cssQuery) and then html():
TestClass:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class TestA {
public static void main(String[] args) throws IOException {
//this is where chromedriver.exe should be
String driverPath = "yourDriverPath";
System.setProperty("webdriver.chrome.driver", driverPath);
WebDriver driver = new ChromeDriver(); ;
driver.get("YourURL");
WebDriverWait wait = new WebDriverWait(driver, 15);
String cssSelector = "span[data-dojo-attach-point=subNumber]";
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssSelector)));
Document doc = Jsoup.connect("YourURL").get();
Element subNumber = doc.selectFirst(cssSelector);
System.out.println(subNumber.html());
}
}
Output:
94607506
Note: I've tried the above in my laptop and it's working.
Use this CSS Selector.
div.subHeaders > div.subHeaderItem > span
String number = doc.select("div.subHeaders > div.subHeaderItem > span").text();
If the page has loaded then you will get the text. Use "Try Jsoup" to verify if you are able to get the text.
Click on this link. Click "Fetch URL" and input the URL of the page you are trying to parse and click "Fetch". Let me know if you are able to get the value.
If you don't mind posting the URL here, post the URL here. We will help you.
Related
hi i'm trying to click on a button using Xpath on chrome browser but from some reason the software does not click on it.
i used the devtools inspect in order to copy the Xpath to the findElement function.
that's the website: https://mynames.co.il/
i'm sorry that's in hebrew...
this photo shows the button ,i marked the button in blue
that's the steps file:
package stepDefinitions;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import cucumber.api.PendingException;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class purchaseDomainSteps {
WebDriver driver;
#Before
public void setup() throws IOException {
System.setProperty("webdriver.chrome.driver", Paths.get(System.getProperty("user.dir")).toRealPath() + "\\src\\test\\java\\drivers\\chromedriver.exe");
this.driver = new ChromeDriver();
this.driver.manage().window().maximize();
this.driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
}
#After()
public void tearDown() {
this.driver.manage().deleteAllCookies();
this.driver.quit();
}
#Given("^I access https://mynames\\.co\\.il$")
public void i_access_https_mynames_co_il() throws Throwable {
driver.get("https://mynames.co.il/");
throw new PendingException();
}
#When("^I click on Login button\\.$")
public void i_click_on_Login_button() throws Throwable {
String path = "/html/body/div[1]/div/div/section[2]/div/div/div[2]/div/div/section/div/div/div[2]/div/div/div/div/div/a/span/span";
//WebDriverWait wait = new WebDriverWait(driver, 5);
driver.findElement(By.xpath(path)).click();
throw new PendingException();
}
that's the runner class:
package runners;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features = { "src/test/java/featurefiles/" }, glue = {
"stepDefinitions" }, monochrome = true, tags = {},
plugin = { "pretty", "html:target/cucumber", "json:target/cucumber.json",
"com.cucumber.listener.ExtentCucumberFormatter:output/report.html" })
public class MainRunner {
}
Hey pls use this Xpath to click that button which you marked in blue colour line
//span[contains(text(),'כניסה')]
After I've check the website (https://mynames.co.il/):
<div class="elementor-button-wrapper">
<a href="https://dash.mynames.co.il/login" target="_blank" class="elementor-button-link elementor-button elementor-size-xs" role="button">
<span class="elementor-button-content-wrapper">
<span class="elementor-button-text">כניסה</span>
</span>
</a>
</div>
I recommend 2 options:
Use the link itself to redirect on login page
String targetPage = driver.findElement(By.xpath("/html/body/div[1]/div/div/section[2]/div/div/div[2]/div/div/section/div/div/div[2]/div/div/div/div/div/a")).getAttribute("href");
driver.navigate().to(targetPage);
(Maybe this is what you want) You click on href or force a href to act like button
driver.findElement(By.xpath("/html/body/div[1]/div/div/section[2]/div/div/div[2]/div/div/section/div/div/div[2]/div/div/div/div/div/a")).click();
The reason that your code is not working is because span that you assume as button, doesn't have any click action meanwhile the click action you hope for is on a href.
// this is just text with style inside span
<span class="elementor-button-text">כניסה</span>
Are you getting any Exception ? If yes, what exception is that ? If no, selenium clicking is happening but the application is not acknowledging the click. So try using javascript executor to perform click as below
WebElement ele = driver.findelement(By.xpath("//span[text()='כניסה']"));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("argument[0].click();",ele);
Even after using the above code, if it doesn't work, then check if you are referring to the right feature and class files in junit runner class cucumberOptions 'glue' and 'features'
One more important tip : I see absolute xpath in your script which will not work if there is a change in the DOM structure in future, So always go for relative xpath
As the element is a dynamic element so to click() on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.elementor-button-link.elementor-button.elementor-size-xs span.elementor-button-text"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//span[#class='elementor-button-text' and text()='כניסה']"))).click();
This question already has answers here:
How to handle HTML constraint validation pop-up using Selenium?
(3 answers)
Closed 3 months ago.
How do I validate the following message? The required class has the floating message.:
try the following, but I get the error "no such alert"
package firsttestngpackage;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginBambu {
public String baseUrl = "http://132.148.19.159:8086/panel/#/login";
String driverPath = "H:\\chromedriver.exe";
public WebDriver driver;
#Test
public void IniciarSesion() {
System.setProperty("webdriver.chrome.driver", driverPath);
driver = new ChromeDriver();
driver.get(baseUrl);
WebElement login = driver.findElement(By.cssSelector("#page-top > div.margen-panel-60.ng-scope > div > div.row.container-fluid.ng-scope > div:nth-child(1) > div > form > button"));
login.click();
String mensaje=driver.switchTo().alert().getText();
System.out.println(mensaje);
}
}
The HTML5 Constraint validation message is the outcome of Constraint API's element.setCustomValidity() method.
Note: HTML5 Constraint validation doesn't remove the need for validation on the server side. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent by non-compliant browsers (for instance, browsers without HTML5 and without JavaScript) or by bad guys trying to trick your web application. Therefore, like with HTML4, you need to also validate input constraints on the server side, in a way that is consistent with what is done on the client side.
Solution
To retrieve the text which results out from the element.setCustomValidity() method, you can use the following solution:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class validationmessage {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
WebDriver driver = new ChromeDriver(options);
driver.get("http://132.148.19.159:8086/panel/#/login");
WebElement username = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.form-control.ng-pristine.ng-invalid.ng-invalid-required.ng-touched[placeholder='Usuario']")));
System.out.println(username.getAttribute("validationMessage"));
}
}
Console Output:
Please fill out this field.
I'm having major issue trying to select menu two elements on a dropdown.I've tried xpaths, link texts and css selector but it wont select either the password button or logout button.
Xpaths used for Password button: "//*[#id='app']/header/div[3]/nav/ul/li/a"
CSS used for Logout button: ["data-logged-in-log-out-button"]
XPath used for Logout button: "//*[#id='app']/header/div[3]/nav/ul/a"
The error im getting for the select password is:
org.openqa.selenium.WebDriverException: unknown error: Element ... is not clickable at point (989, 233).
Other element would receive the click: ...
Please try with the below XPath along with the explicit wait condition.
XPath:
//*[contains(text(),'Log out')]
Can you please try -
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class A {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("url here");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Log Out")));
driver.findElement(By.linkText("Log Out")).click();;
}
}
If it still doesn't work, please try -
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class A {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("url here");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", driver.findElement(By.linkText("Log Out")));
}
}
I am trying to close pop up using selenium web driver with java. I have tried different ways, but unable to succeed. Please help me.
package Demo;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class YahooTest {
public static void main(String[] args) throws InterruptedException {
FirefoxDriver obj = new FirefoxDriver();
String url = "https://www.planyourjourney.com/";
obj.get(url);
obj.manage().window().maximize();
obj.findElement(By.xpath("html/body/div[12]/div/div/div[9]")).click();
obj.findElementByClassName("dyna-link-new-registration").click();
obj.findElement(By.linkText("B2B Login")).click();
Thread.sleep(4000);
obj.findElement(By.id("userid")).clear();
obj.findElement(By.id("userid")).sendKeys("1592jet#gmail.com");
obj.findElement(By.id("ulPassword")).clear();
obj.findElement(By.id("ulPassword")).sendKeys("spyj01");
obj.findElement(By.name("Next")).click();
Thread.sleep(2000);
obj.findElement(By.id("affilitetrainadvpage"));
Alert alert = obj.switchTo().alert();
alert.dismiss();
}
}
I have seen the source code of the web page and could not find any alert in it.
The pop-up is actually written inside a div tag.
Hence, remove the codes related to alert and use below code which uses xpath.
obj.findElement(By.xpath("//*[#id='affilitetrainadvpage']/span/a/img")).click();
I want to open a a link on a webpage. The link appears to be within a unordered list which resides within in a tag. The url to the web page is selftechy dot com. The tabs are home, about, selenium.
I attempted to open the link using driver.findElement(By.linkText("Selenium")); but page seems like lost its styling. I also tried with xpath method, but it doesn't work either. Please explain to me why it doesn't work and how should I modify the code to make it work properly. Thanks for your help.
HTML code fragment:
<body class="custom">
<div id="container">
<div id="page">
<ul class="menu">
<li class="tab tab-home current">Home</li>
<li class="tab tab-1">About</li>
<li class="tab tab-2">Selenium</li>
</ul>
webdriver code to open the link
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import org.junit.Before;
import org.junit.After;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class selftechyTestng
{
private WebDriver driver;
private String baseUrl;
#Before
public void setUp() throws Exception
{
driver = new FirefoxDriver();
baseUrl = "http://selftechy.com/";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Test
public void searchElements() throws Exception{
driver.get(baseUrl);
//use By.linkText method the page lost its styling
driver.findElement(By.linkText("Selenium"));
//use xpath method to open the link doesn't work either
List<WebElement> elements = driver.findElements(By.xpath("//div[#id=page]/*[3]")).click();
driver.findElement(By.xpath("//div[#id=page]/*[3]")).click();
}
}
Why do you search for the div and then the child element - Is there any particular reason? I don't see any advantage and certainly you are then not getting the a element which you actually want to click. In my opinion it is much simpler to use
driver.findElement(By.xpath("//a[#title = 'Selenium']")).click();
Using your approach you have to use
driver.findElement(By.xpath("//div[#id = 'page']/ul/li[3]/a")).click();
You can also use this xpath:
"//a[text()='Selenium']"
This will find the link with text = Selenium
Below code will open the link in new window and prints the title and url of the newly opened window.
String defaultwindow = "";
#Test(description="Main Page")
public void UserOnMainPage()
{
driver.get("http://yoururl.com");
defaultwindow = driver.getWindowHandle();
String selectAll = Keys.chord(Keys.SHIFT,Keys.RETURN);
driver.findElement(By.linkText("linkname")).sendKeys(selectAll);
printTitleandUrlofNewlyOpenedwindow();
}
private void printTitleandUrlofNewlyOpenedwindow()
{
Set<String> windowHandles1 = driver.getWindowHandles();
int size = windowHandles1.size();
System.out.println(size);
for (String string : windowHandles1)
{
driver.switchTo().window(string);
if(string.equals(defaultwindow))
{
System.out.println("On Main Window");
Reporter.log("On Main Window");
}
else
{
String title=driver.getTitle();
System.out.println(title);
Reporter.log(title);
String recipeUrl = driver.getCurrentUrl();
System.out.println(recipeUrl);
Reporter.log(recipeUrl);
}
}
driver.switchTo().window(defaultwindow);
}
Below code will open the link in new Tab.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);