【问题标题】:How would I click this href link in Selenium?我将如何在 Selenium 中单击此 href 链接?
【发布时间】:2015-07-20 17:43:16
【问题描述】:

代码如下:

<div class="padding">
      <a href="javascript:FreshCoShowEFlyerOverlay()">
            <img alt="Example" src="http://freshco.wpengine.com/wp-content/uploads/2015/05/week-flyer-left.jpg" height="158" width="280">
      </a>
</div>

我正在尝试单击 href。我已经尝试过了,但它不起作用:

driver.findElement(By.xpath("//href[text()='javascript:FreshCoShowEFlyerOverlay']")).click();

【问题讨论】:

  • 你说的不起作用是什么意思?你有错误吗?什么都没有发生吗?
  • href 不是标签,而是属性。
  • 它抛出 org.openqa.selenium.NoSuchElementException

标签: java html selenium selenium-webdriver webdriver


【解决方案1】:

使用这个:

driver.findElement(By.xpath("//a[@href='javascript:FreshCoShowEFlyerOverlay']")).click();

相对于:

driver.findElement(By.xpath("//href[text()='javascript:FreshCoShowEFlyerOverlay']")).click();

【讨论】:

  • 这给了我这个错误:线程“main”中的异常 org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//a [@href='javascript:FreshCoShowEFlyerOverlay']"}
  • 愿你多出一个具有相同href的元素。你能发布这个 Html 代码的父标签吗?
  • //img[@alt='Example']。一旦尝试这个。
  • 这是因为她忘记在 xpath 表达式的末尾附加()。或者你可以使用这个:"//a[contains(@href, 'javascript:FreshCoShowEFlyerOverlay')]"
【解决方案2】:

作为另一个变体:

driver.findElement(By.CssSelector("a[href*='FreshCoShowEFlyerOverlay']")).click();

【讨论】:

    猜你喜欢
    • 2015-08-18
    • 2021-12-03
    • 2020-09-23
    • 2017-12-25
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 2013-04-24
    • 2018-02-08
    相关资源
    最近更新 更多