xpath "and"/condition查询如何正确进行?

How to do xpath "and" / condition query correctly?

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

这里是link(最左边的选项):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()

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

TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type.

我认为您试图在不传递 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();

我刚刚尝试了下面的 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

最小工作 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