【问题标题】:My question about xpath not working on Selenium我关于 xpath 不适用于 Selenium 的问题
【发布时间】:2018-11-05 16:59:42
【问题描述】:

我正在尝试使用 Selenium 的 xpath 从网站下载特定日期的文件,如下所示。我正在使用它从网站表单中找到我想要的链接。

driver.findElement(By.xpath("//tr[td[contains(.,'10/30/2018')] and @class='Row ']//span")).click();

当我使用 xpath 在 Chrome 浏览器中直接搜索 HTML 时,它给了我想要的结果。但是,如果我在 java 程序中使用 Selenium'xpath(Web 驱动程序是 Chrome 的)来定位元素,我得到“没有这样的元素异常”。我已经尝试使用

等待更长的网络加载时间
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

但它不起作用。

谁能告诉我为什么?

我看到该链接位于“iframe”标签中。这是我应该先处理的事情吗?

网页结构基本是这样的

<tr>
  <tr class="Row ">
    <td>10/30/2018 9:00:00 PM<td>
    <td>
      <span>
        <input type="submit" value="Download"></input>
        <input type="hidden"></input>
      </span>
    </td>
  </tr>
  <tr class="Row ">
    <td>10/27/2018 9:00:00 PM<td>
    <td>
      <span>
        <input type="submit" value="Download"></input>
        <input type="hidden"></input>
      </span>
    </td>
  </tr> 
</tr> 

我也试过了,还是不行。

driver.findElement(By.xpath("//tr[td[contains(.,'10/30/2018')] and @class='Row ']//input[@type='submit']")).click();

【问题讨论】:

  • 你能展示下这个问题的 html 结构吗?也许 xpath 是错误的......
  • 我已经添加了结构。我认为我的 xpath 是正确的,因为当我直接使用它在网站中搜索时它会起作用
  • 试试这个://tr/td[contains(text(),'10/30/2018') and contains(@class,'Row')]/../td/span
  • 就像在网站上“检查元素”和“Ctrl + F”并输入xpath,并找到所需的元素。它只是在我的 java 程序中使用 Selenium 不起作用。
  • implicitWait() 只等待 DOM 被加载,但您正在寻找的 //tr 元素似乎是动态加载的。您是否尝试过使用 WebDriverWait() 显式等待元素?

标签: java selenium selenium-webdriver xpath selenium-chromedriver


【解决方案1】:

我的问题解决了。我找不到该元素的原因是它位于 iframe 标记中。这意味着它是当前网站中的另一个网站。为了解决这个问题,我需要先使用 switchTo 函数去那个网站,然后我才能处理它。

driver.switchTo().frame(driver.findElements(By.tagName("iframe")).get(0)); 

【讨论】:

    猜你喜欢
    • 2013-12-19
    • 2017-08-13
    • 2021-01-01
    • 2013-05-14
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    相关资源
    最近更新 更多