Clicking on a hypertext link using XPath

2020-04-16 06:09发布

问题:

Apologies if this is a dumb question - I'm new to Selenium.

I have a web page I'm testing that has a few hypertext links in a table. The HTML looks like this:

<table>
  <thead>
    <tr>
      <td><b>History</b></td>
      <td><b>Attributes</b></td>
      <td><b>Xml</b></td>
    </tr>
  </thead>
  <tbody>    
    <tr>
      <td><a href=link here>Show</a></td> 
      <td><a href=link here>Show</a></td>
      <td><a href=link here>Show</a></td> 
    </tr>
  </tbody>
</table>

I want to test a click on each of the 'Show' links. They all have the same text, so I can't reference them by linktext. I've been referencing them by XPath, so that:

driver.findElement(By.xpath("//div[@id='content']/div/form/div/table[2]/thead/tr/td[1]").getText()

correctly returns 'History' and

driver.findElement(By.xpath("//div[@id='content']/div/form/div/table[2]/tbody/tr/td[1]").getText()

correct returns 'Show'.

So I would think that:

driver.findElement(By.xpath("//div[@id='content']/div/form/div/table[2]/tbody/tr/td[1]")).click()

would click on the 'Show' link in the first column. But it doesn't - nothing happens.

If I do:

driver.findElement(By.linkText("Show")).click()

it clicks on the first 'Show' link, which is what I expect.

I can also do:

driver.findElement(By.xpath("//div[@id='content']/div/form/div/table[2].1.0")).click()

and that works, as does

driver.findElement(By.xpath("(//a[contains(text(),'Show')])[2]")).click()

So, to sum, all of these work:

driver.findElement(By.linkText("Show")).click()
driver.findElement(By.xpath("//div[@id='content']/div/form/div/table[2].1.0")).click()
driver.findElement(By.xpath("(//a[contains(text(),'Show')])[1]")).click()

but this doesn't:

driver.findElement(By.xpath("//div[@id='content']/div/form/div/table[2]/tbody/tr/td[1]")).click()

Why?

回答1:

You can gather all the links together by using findElements and then iterate through the array.

Example - List<WebElement> inputs = driver.findElements(By.xpath("//input"));

and in your case

List<WebElement> links = driver.findElements(By.linkText("Show"));

and then iterate through links and click on each one of them



回答2:

Notice that the expression in question

driver.findElement(By.xpath("//div[@id='content']/div/form/div/table[2]/tbody/tr/td[1]")).click()

selects a td element, in case of which no link or event is defined. While clicking it in browser should open a link, it will happen only because you're effectively clicking what's inside the tag as well as the td itself. The code above only clicks the td, ignoring its content.

You have to go one step deeper, to the a element within your currently selected td. Like this:

driver.findElement(By.xpath("//div[@id='content']/div/form/div/table[2]/tbody/tr/td[1]/a")).click()


回答3:

List links = driver.findElements(By.tagName("a"));

then iterate through links and click on each one of them using for loop