Python Selenium WebDriver 点击功能
有没有人知道怎么用Python的webdriver点击一个链接,依据的是它的href属性。在waitr-webdriver
中,你可以这样做:
browser.link(:href => "http://www.testsite.com/pageOne.html").click
但是我在Python的webdriver中找不到类似的功能。这里有一些方法:
find_element_by_class_name
find_element_by_css_selector
find_element_by_id
find_element_by_link_text
find_element_by_name
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_xpath
这些方法都很好,但我测试的网站的链接没有ID或类名。所以这些链接唯一的特点就是它们的href网址。
任何帮助都会非常感谢。
1 个回答
6
在后台,watir-webdriver 正在把查找链接的请求(这个链接的 href 属性是某个特定值)转换成 WebDriver 的一种查找方式,叫做 find-by-XPath。要在你自己的代码中模仿这个过程,使用 Python 的正确方法是:
# assume driver is an instance of WebDriver
# NOTE: this code is untested
driver.find_element_by_xpath(".//a[@href='http://www.testsite.com/pageOne.html']")
另外,你也可以使用 CSS 选择器(在 IE 浏览器上会更快),方法如下:
# again, assume driver is an instance of WebDriver
# NOTE: this code is untested
driver.find_element_by_css_selector("a[href='http://www.testsite.com/pageOne.html']")