Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking on text in between SPAN tags using Selenium Webdriver (java)

HTML code looks like this:

<td id="id26a" class="doclisting-name link" style="width: 319px; min-width: 319px;"> 

<span id="id26b" title="Document">
<span class="ie-fallback-marker">
  words

</span></span></td>

I cannot search for Element ID, as it changes all the time. I cannot search for the element's class, as there are multiples which could change locations.

I want to be able to click on "WORDS" in between the SPAN tags. Is this at all possible?

This is what I used so far, but neither seems to work:

//string document is words.
   public void testscenario123(String document)      throws Throwable {
    Thread.sleep(3000);
    driver.findElement(By.linkText(document)).click();
}

or

  //string document is words.
 public void testscenario124(String document) throws Throwable {
    Thread.sleep(3000);
    driver.findElement(By.xpath("//*[contains(@span,'"+document+"')]")).click();
}
like image 773
user3356141 Avatar asked Mar 03 '14 12:03

user3356141


2 Answers

You can select xpath via text and normalize-space will strip white space:

  //string document is words.
 public void testscenario124(String document) throws Throwable {
    Thread.sleep(3000);
    driver.findElement(By.xpath("//*[normalize-space()='"+document+"']")).click();
}

You may also wish to consider waiting for the element to appear instead of declaring an explicit sleep

like image 135
Robbie Wareham Avatar answered Sep 28 '22 04:09

Robbie Wareham


I suspect the element is taking more than 3 seconds to appear.Hence the following exception is thrown.

Element is not currently visible and so may not be interacted with

To avoid this exception implicit or explicit wait must be used.

new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(., \"" + document + "\")]"))).click();

As RobbieWareham has mentioned,even i'm interested to know more about this waiting makes a ridiculous piece of code?

Through Selenium Webdriver,we are just trying to imitate how a user would work.Even he/she has to wait for the element to appear to perform some operation.

like image 22
Amith Avatar answered Sep 28 '22 04:09

Amith