【问题标题】:Xpath locator unable to detect the elementXpath 定位器无法检测到元素
【发布时间】:2023-03-26 07:46:01
【问题描述】:

我正在尝试使用 selenium 选择一个按钮,但是我相信我在编写 xpath 时做错了,谁能帮我解决这个问题,我需要选择货币欧元。 链接:-https://www.booking.com/

我要选择的定位器

我写的定位器

USD = self.find_element_by_xpath(f"//a[contains(text(),'selected_currency='Euro']")
USD.click()

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

    下面的xpath

    //a[contains(@href,'EUR') and starts-with(@class,'bui-list')]
    

    在 HTML DOM 中出现两次。

    检查步骤:

    Press F12 in Chrome -> 转到element 部分 -> 做一个CTRL + F -> 然后粘贴xpath 看看,如果你想要的element 用@ 得到突出显示 987654327@匹配节点。

    如果您想选择 Suggest for you 中的第一个,则无需对 XPath 执行任何操作。

    @pmadhu 的回答具有误导性,因为当与 Selenium 一起使用时,为什么有人会在 XPath 中查找第一个索引?如果有多个匹配节点,Selenium 总是会选择第一个元素,所以我真的没有任何意义为什么有人会使用[1]

    尽管如此,

    点击为您推荐欧元:

    try:
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@href,'EUR') and starts-with(@class,'bui-list')]"))).click()
    except:
        pass
    

    进口:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

    如果您希望点击欧元的第二个匹配节点,

    在这种情况下,使用索引 2 是有意义的。

    XPath 看起来像这样:

    (//a[contains(@href,'EUR') and starts-with(@class,'bui-list')])[2]
    

    【讨论】:

    • 感谢@cruisepandey 很好地解释了这一点,但是您提到的第二个代码不起作用 (//a[contains(@href,'EUR') 并开始于(@class,'bui -list')])[2]
    【解决方案2】:

    您要查找的文本:selected_currency='EUR' 位于a 标记的data-modal-header-async-url-param 参数中。你应该在上面运行contains

    编辑: 定位器://a[contains(@data-modal-header-async-url-param, 'selected_currency=EUR')]

    【讨论】:

    • 我没听懂,如果可能的话,请把定位器写在这里
    • 它现在就在那里
    【解决方案3】:

    如前所述,selected_currency=EUR 在属性中 - data-modal-header-async-url-param

    但是您可以使用以下代码选择所需的选项。

    EUR 选项的 xpath 可以是 - //div[contains(text(),'EUR')]。因为它使用这个 xpath-(//div[contains(text(),'EUR')])[1] 突出显示 DOM 中的 2 个元素。找到独特的定位器很重要。 Link to refer

    # Imports required for Explicit wait
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    driver.get("https://www.booking.com/")
    
    wait = WebDriverWait(driver,30)
    
    # Click on Choose currency option
    wait.until(EC.element_to_be_clickable((By.XPATH,"//span[@class='bui-button__text']/span[contains(text(),'INR')]"))).click()
    
    # Click on the EUR option.
    euro_option = wait.until(EC.element_to_be_clickable((By.XPATH,"(//div[contains(text(),'EUR')])[1]")))
    euro_option.click()
    

    【讨论】:

    • 谢谢你解释得这么好@pmadhu
    猜你喜欢
    • 2021-08-01
    • 2020-03-01
    • 2021-02-11
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 2018-03-15
    相关资源
    最近更新 更多