Reputation: 1
I would like to use a function to show on the screen the current value of a dropdown list, because the Selenium code isn't pretty.
The following works perfectly in my main script:
new Select(driver.findElement(By.id("secId:mainBody:vboxlist:s_m9_aa2::content"))).selectByVisibleText(contract.getCreditype());
But using the function, it doesn't work:
writeScreen("Description : ", "secId:mainBody:vboxlist:s_m9_aa2::content");
public void writeScreen(String description, String identifiant) {
String xpath="//*[@id=\\\""+identifiant+"\\\"]";
Select select = new Select(driver.findElement(By.xpath(xpath)));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(description+defaultItem);
I got the following error:
org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression //[@id=\"secId:mainBody:vboxlist:s_m9_aa2::content\"] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//[@id=\"secId:mainBody:vboxlist:s_m9_aa2::content\"]' is not a valid XPath expression.
When I checking the XPATH, it's exactly the same as in my first working example.
Upvotes: 0
Views: 93
Reputation: 13712
Your xpath is wrong, please change String xpath="//*[@id=\\\""+identifiant+"\\\"]";
as following:
String xpath="//*[@id='"+identifiant+"']";
Upvotes: 1
Reputation: 195
unless your xpath is wrong, its probably because the element hasn't loaded yet?
So sometimes the script will run faster than the response time of the webpage.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Add this line after searching for the xpath but before taking action upon it, so look for it, wait, then action, you can add more functionality to the wait however this will test whether or not this is the problem.
writeScreen("Description : ", "secId:mainBody:vboxlist:s_m9_aa2::content");
public void writeScreen(String description, String identifiant) {
String xpath="//*[@id=\\\""+identifiant+"\\\"]";
Select select = new Select(driver.findElement(By.xpath(xpath)));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(description+defaultItem);
Is how your code might look
Another issue i have just noticed, you are most likely doing the xpath wrong, when declaring it into your variable it should look like this
String xpath="//*[@id=\\\"'+identifiant+'\\\"]";
the way you are doing it, is making +identifiant+ a function rather than a string linking to an xpath.
Upvotes: 0