Clicking on a hypertext link using XPath

后端 未结 3 370
予麋鹿
予麋鹿 2021-01-21 20:16

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:

相关标签:
3条回答
  • 2021-01-21 20:50

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

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

    0 讨论(0)
  • 2021-01-21 20:51

    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()
    
    0 讨论(0)
  • 2021-01-21 20:54

    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

    0 讨论(0)
提交回复
热议问题