【问题标题】:using an xpath in selenium python在 selenium python 中使用 xpath
【发布时间】:2014-09-15 05:53:11
【问题描述】:

我在 Firefox 中使用 firebug 为一个没有分配 ID 的链接获取 xpath。该链接是一个带有图像作为实际按钮的 javascript 链接。我希望能够单击此链接,但它不起作用。

实际的xpath是'/html/body/div[2]/div/div/div[3]/div/div/table/tbody/tr[1]/td[2]/form/table/tbody /tr[1]/td/div[1]/div/table/thead/tr[2]/th[1]/a/img'

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()

URL = 'http://example.com'

driver.set_window_size(1024, 768)
driver.get(url)

link = driver.find_element_by_xpath(//*[@id="//html/body/div[2]/div/div/div[3]/div/div/‌​table/tbody/tr[1]/td[2]/form/table/tbody/tr[1]/td/div[1]/div/table/thead/tr[2]/th‌​[1]/a/img"])
for link in links:
 link.click()

我收到以下错误: is either invalid or does not result in a WebElement. The following error occurred:\nInvalidSelectorError: Unable to locate an element with the xpath expression //*[@id=/html/body/div[2]/div/div/div[3]/div/div/table/tbody/tr[1]/td[2]/form/table/tbody/tr[1]/td/div[1]/div/table/thead/tr[2]/th[1]/a/img because of the following error:\n[Exception... "The expression is not a legal expression." code: "12" nsresult: "0x805b0033 (SyntaxError)" location: "<unknown>"]' ; Stacktrace:

<a onclick="if(typeof functionx == 'function'){functionx(document.getElement…,'liststuff','');}return false" href="#">

   <img style="border: 0px;" onmouseover="this.src='/add-hover.gif';" onmouseout="this.src='/add.gif';" alt="Add" src="/icon-add.gif"></img>

</a>

【问题讨论】:

  • 您能否显示包含该链接的相关 html 代码,或提供该网站的链接?谢谢。
  • @alecxe 抱歉,我无法提供网址,因为它位于公司的内部服务器上。
  • 猜测:&lt;a&gt; 标签可能有一个img 属性,而不是嵌套的&lt;img&gt; 标签。如果是这样,请尝试在 XPath 的末尾将 a/img 更改为 a/@img
  • @user2242044 您拥有的 xpath 非常脆弱。提供一个 html 代码,以便我们可以在那里看到链接。
  • @alecxe 我在原帖中添加了元素,但无法添加完整的html代码

标签: python python-2.7 selenium xpath selenium-webdriver


【解决方案1】:

依赖于它的父元素和属性,而不是拥有元素的绝对路径:

link = driver.find_element_by_xpath('//a[@onclick and @href = "#" and img/@alt = "Add"]')

【讨论】:

  • 这个执行现在将编码问题,但不会打开当我手动单击链接时打开的页面。
  • @user2242044 我已经更新了 xpath 表达式,请检查。
  • 还是一样的结果。没有错误但没有打开链接。 PyCharm 给出以下结果Process finished with exit code 0
  • 这成功了!我不小心删除了link.click() 行。太感谢了。标记为最佳答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 2020-03-07
  • 1970-01-01
  • 2020-09-04
  • 2012-12-21
  • 1970-01-01
  • 2020-12-29
相关资源
最近更新 更多