【问题标题】:Python Selenium SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//div[contains(@class, 'product-card__subtitle')Python Selenium SyntaxError:无法在“文档”上执行“评估”:字符串'//div [包含(@class,'product-card__subtitle')
【发布时间】:2020-08-15 03:26:53
【问题描述】:

试图获取 div 类的 XPath 和 div 内的文本。这两个 div 是:

<div class="product-card__subtitle">Women's Shoe</div>
<div class="product-card__subtitle">Men's Shoe</div>

出现硒错误的 Xpath 是:

driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text("
                                                      ")='Women's Shoe']")

driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text()='Men's "
                                                    "Shoe']")

我正在尝试获取“女鞋”部分的路径和“男鞋”部分的另一条路径

【问题讨论】:

    标签: python selenium selenium-webdriver xpath xpath-1.0


    【解决方案1】:

    此错误消息...

    SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//div[contains(@class, 'product-card__subtitle')
    

    ...暗示您使用的 XPath 不是有效的XPath 表达式


    解决方案

    要定位所需的元素,您可以使用以下基于Locator Strategies

    • Women's Shoe:

      driver.find_element_by_xpath("//div[@class='product-card__subtitle' and contains(., \"Women's Shoe\")]")
      
    • Men's Shoe:

      driver.find_element_by_xpath("//div[@class='product-card__subtitle' and  contains(., \"Men's Shoe\")]")
      

    参考文献

    您可以在以下位置找到一些相关的详细讨论:

    【讨论】:

      【解决方案2】:

      根本原因是文本有符号'
      虽然您可以优化其他 xpath 语法表达式,但您不必这样做。

      编辑 1:

      driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text()=\"Women's Shoe\"]")
      
      driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text()=\"Men's Shoe\"]")
      

      我认为下面是正确的,但是在 chrome 控制台中验证时,我仍然收到错误“不是有效的 XPath 表达式”

      driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text()='Women\'s Shoe']")
      
      driver.find_element_by_xpath("//div[contains(@class, 'product-card__subtitle') and text()='Men\'s Shoe']")
      

      【讨论】:

      • 我收到此错误selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //div[contains(@class, 'product-card__subtitle') and text()='Men's Shoe'] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//div[contains(@class, 'product-card__subtitle') and text()='Men's Shoe']' is not a valid XPath expression. (Session info: chrome=84.0.4147.125)
      • 是的,对不起。原始答案仍然有语法错误,我会修复它。事实上,我认为较短的 xpath 应该可以正常工作,只需尝试 "//div[text()=\"Men's Shoe\"]"
      猜你喜欢
      • 2021-08-30
      • 1970-01-01
      • 2019-02-03
      • 2019-12-25
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      相关资源
      最近更新 更多