Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11295

Clicking an image using Selenium in Python throwing invalid xpath

This is what I have

for arrow in self.driver.find_elements_by_xpath("//img[contains(@src, 'disclosure_closed.gif')]/"):
            arrow.click()

But it's throwing this to me

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //img[contains(@src, 'disclosure_closed.gif')]/ because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//img[contains(@src, 'disclosure_closed.gif')]/' is not a valid XPath expression.
  (Session info: chrome=42.0.2311.135)
  (Driver info: chromedriver=2.15.322448 (52179c1b310fec1797c81ea9a20326839860b7d3),platform=Windows NT 6.1 SP1 x86_64)

I've also tried doing this:

image_url = "http://example.com/disclosure_closed.gif"
for arrow in self.driver.find_elements_by_xpath("//img[@src='%s']/" %(image_url)):
    arrow.click()

This is the html:

<img align="top" style="cursor:pointer;" onclick="disclose('44');" id="44disclosure" src="http://example.com/disclosure_closed.gif">

Upvotes: 1

Views: 822

Answers (2)

Javier Velasquez
Javier Velasquez

Reputation: 59

looks like you already got your answer. But you don't need to be using xpath for that identifier. xpaths are slower then css and (generally) not as reliable either. You could make the following css selector to identify the same element:

[src*='disclosure_closed.gif']

or (for images specifically)

img[src*='disclosure_closed.gif']

Upvotes: 1

eLRuLL
eLRuLL

Reputation: 18799

remove / at the end of the xpath.

Upvotes: 1

Related Questions