在Selenium Python中使用XPath
我在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()
但是我遇到了以下错误:
无效或者没有找到WebElement。发生了以下错误:\nInvalidSelectorError: 无法根据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找到元素,原因是:\n[Exception... "这个表达式不是合法的表达式。" code: "12" nsresult: "0x805b0033 (SyntaxError)" location: "<unknown>"]' ; 堆栈跟踪:
<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>
1 个回答
4
与其使用元素的绝对路径,不如依赖它的父元素和属性来定位:
link = driver.find_element_by_xpath('//a[@onclick and @href = "#" and img/@alt = "Add"]')