selenium-Python, how to click the logout image button

12,474

I'd rather use css selector:

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

See find_element_by_css_selector.


If you want use xpath, use following xpath expression (There's a typo in the code: images -> img):

driver.find_element_by_xpath('//a[img/@src="resources/img/logout.png"]').click()
Share:
12,474
user3305223
Author by

user3305223

Updated on June 04, 2022

Comments

  • user3305223
    user3305223 almost 2 years

    the html is below:

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

    python is

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

    it giving error as below

       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)