【问题标题】:How to do xpath "and" / condition query correctly?如何正确进行xpath“和”/条件查询?
【发布时间】:2019-07-31 15:09:46
【问题描述】:

我正在尝试在 amazon.fr 上的主要选项上设置复选标记。

这是链接(主要选项在左侧):https://www.amazon.fr/gp/browse.html?node=2036893031

这是显示我要勾选的字段的图像:https://ibb.co/ZY3mK3Z

我几乎可以正常工作了。但它不适用于所有亚马逊类别,这就是我添加“and”运算符的原因。这是我的 xpath 查询:

driver = webdriver.Chrome()
driver.get(category_url)
driver.find_element_by_xpath('//*[@id="leftNav"]/h4[text()="%s"]/following-sibling::ul//input[contains(@name, "s-ref-checkbox-")] and //*[@id="leftNav"]/h4[text()="%s"]/following-sibling::ul//input[contains(@name, "s-ref-checkbox-")]//i[contains(@class, "icon-prime")]' % ("Option d'expédition", "Option d'expédition"))
driver.click()

如何正确格式化我的查询?和运算符甚至是必要的吗?我收到以下错误消息:

TypeError:无法对“文档”执行“评估”:结果是 不是节点集,因此无法转换为所需的类型。

【问题讨论】:

标签: python selenium xpath amazon


【解决方案1】:

我认为您正在尝试在不传递 WebElement 的情况下单击。 您可以根据旁边 Prime 标签的位置找到复选框。

试试下面的xpath,

myprime = driver.find_element_by_xpath("//*[contains(@class,'icon-prime a-icon-small s-ref-text-link')]/parent::span/parent::label/input")
myprime.click();

【讨论】:

  • 非常感谢。现在它起作用了!我已经尝试了几个小时才能让它正确。
【解决方案2】:

我刚刚尝试了下面的 XPath,它唯一地定位了元素

//label[.//i[contains(@class, 'a-icon-prime')]]/input
^ find a LABEL tag
       ^ that has a child I tag
            ^ that contains the class 'a-icon-prime' (indicating the prime logo)
                                               ^ then find an INPUT under the LABEL

【讨论】:

    【解决方案3】:

    最小的工作 XPath locator 将是:

    //i[contains(@class,'small') and contains(@class,'prime')]
    

    为了获得更好的稳健性和可靠性,我建议将其包装成 Explicit Wait,例如:

    prime = WebDriverWait(driver, 10).until(
        expected_conditions.presence_of_element_located((By.XPATH, "//i[contains(@class,'small') and contains(@class,'prime')]")))
    prime.click()
    

    更多信息:How to use Selenium to test web applications using AJAX technology

    【讨论】:

      猜你喜欢
      • 2013-10-22
      • 2021-10-28
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多