【问题标题】:How to click a hyperlink without any link text如何单击没有任何链接文本的超链接
【发布时间】:2019-01-10 00:04:27
【问题描述】:

我正在尝试单击没有链接文本的超链接。

我有:

 <a id="fontColor" href="f?p=420181023:1:12264109389989:1416222:NO::P1_SEMCODE:20190">
     <strong>Check</strong>
 </a>

我试过了:

driver.findElement(By.xpath("//a[@href='f?p=420181023:1:12264109389989:1416222:NO::P1_SEMCODE:20190']")).click();

导致 No.SuchElementException

driver.findElement(By.id("fontColor")).click();

什么都不做

我从不同的网站阅读了不同的材料,但似乎没有提到没有链接文本的超链接。有没有替代

By.xpath()
By.id() 
By.linkText() 

来源:

How to click a href link using Selenium

https://www.w3schools.com/html/html_links.asp

【问题讨论】:

  • 你提供的stackoverflow链接说要删除href后面的空格,但看起来你没有这样做。
  • 这是一个错字,现已修正。谢谢。
  • By.partialLinktext("Check") 怎么样?
  • No.SuchElementException 即使使用 partialLinktext。
  • 它应该可以工作。您确定您在包含该元素的页面上吗?我还会检查您是否在 iframe 中。您需要先切换到 iframe。

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

所需的元素看起来是一个动态元素,因此调用 click() 您需要诱导 WebDriverWait 以使所需的 元素可点击,您可以使用以下解决方案:

  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a#fontColor[href*='P1_SEMCODE']>strong"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@id='fontColor' and contains(@href, 'P1_SEMCODE')]/strong[contains(., 'Check')]"))).click();
    

【讨论】:

  • href* 代表/意味着什么,我从未在 css 或 xpath 中看到带有属性名称的通配符?请确认。
  • @AmitJain cssSelector 支持通配符,cssSelector 中的* 相当于XPath 中的contains()。检查这个discussion
猜你喜欢
  • 2018-06-26
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多