selenium-Python,如何单击注销图像按钮

时间:2014-02-13 09:02:18

标签: python selenium xpath

html如下:

<li class="logout"> <a href="#/logout"><img src="resources/img/logout.png"/></a></li>

python是

driver.find_element_by_xpath("//img[contains(@src='resources/images/logout.png')]/parent::a").click()

它给出错误如下

   driver.find_element_by_xpath("//img[contains(@src='resources/images/logout.png')]/parent::a").click()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 221, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 681, in find_element
    {'using': by, 'value': value})['value']
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 164, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 164, in check_response
    raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: u'Unable to locate element: {"method":"xpath","selector":"//img[contains(@src=\'resources/images/logout.png\')]/parent::a"}' ; Stacktrace: 
    at FirefoxDriver.prototype.findElementInternal_ (file:///tmp/tmpu3t8lf/extensions/fxdriver@googlecode.com/components/driver_component.js:8860)
    at fxdriver.Timer.prototype.setTimeout/<.notify (file:///tmp/tmpu3t8lf/extensions/fxdriver@googlecode.com/components/driver_component.js:396) 

2 个答案:

答案 0 :(得分:3)

我宁愿使用css选择器:

driver.find_element_by_css_selector('li.logout>a').click()

请参阅find_element_by_css_selector


如果你想使用xpath,请使用以下xpath表达式(代码中有一个拼写错误:images - &gt; img):

driver.find_element_by_xpath('//a[img/@src="resources/img/logout.png"]').click()

答案 1 :(得分:0)

请尝试driver.find_element_by_xpath("//img[@src='resources/images/logout.png']/parent::a").click()