【问题标题】:Clicking an image using Selenium in Python throwing invalid xpath在 Python 中使用 Selenium 单击图像会抛出无效的 xpath
【发布时间】:2015-05-02 16:23:55
【问题描述】:

这就是我所拥有的

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

但它把这个扔给我

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)

我也试过这样做:

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

这是html:

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

【问题讨论】:

  • 尽量不要用/结束xpath
  • @eLRull wow.. 就是这样:|呃..好吧,我觉得自己很愚蠢。你能提交这个作为答案吗?

标签: python selenium xpath


【解决方案1】:

删除 xpath 末尾的 /

【讨论】:

    【解决方案2】:

    看起来你已经得到了答案。但是您不需要为该标识符使用 xpath。 xpaths 比 css 慢,而且(通常)也不那么可靠。您可以制作以下 css 选择器来识别相同的元素:

    [src*='disclosure_closed.gif']
    

    或(专门针对图片)

    img[src*='disclosure_closed.gif']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2017-05-29
      • 2019-01-29
      相关资源
      最近更新 更多