2014-02-13 67 views
0

的HTML低於:硒的Python,如何單擊註銷圖像按鈕

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

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/[email protected]/components/driver_component.js:8860) 
    at fxdriver.Timer.prototype.setTimeout/<.notify (file:///tmp/tmpu3t8lf/extensions/[email protected]/components/driver_component.js:396) 

回答

2

我會而是使用css選擇器:

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

參見find_element_by_css_selector


如果你想使用XPath,使用下面的XPath表達式(有代碼中的一個錯字:images - >img):

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

無需兩個嵌套方括號中,您可以使用'/ a [img/@ src =「resources/img/logout.png」]作爲XPath。 – Robin

+0

@Robin,你說得對。謝謝你的啓發。我根據你的評論更新了答案。 – falsetru

0

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