python - 在 selenium python 中使用 xpath

标签 python python-2.7 selenium xpath selenium-webdriver

我在 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>

最佳答案

与其拥有元素的绝对路径,不如依赖它的父元素和属性:

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

关于python - 在 selenium python 中使用 xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24920781/

相关文章:

python - 如何修复 Google Cloud Vision 的段错误?

python - 如何通过代理使用 Boto3 S3 连接?

python - 使用 reduce 和装饰器在 Python 中级联函数

javascript - 无法获取一页中多个选项卡的总记录值

python - 用 selenium 抓取,无法获得单击按钮并用我想要的数据加载隐藏表

python - 如果 getopt 中未设置 cmd 参数,如何设置默认值

python - Scrapy:使用特定的 python 版本

python - 在 Tkinter 的 Checkbutton 中更改复选框相对于文本的位置

ruby-on-rails - 需要自动化的 Rails gem 替代 Mechanize 用于非测试目的

python + Selenium webdriver : using authenticate method