繁体   English   中英

无法通过Selenium Webdriver python中的XPath选择元素

[英]Unable to select an element via XPath in selenium Webdriver python

我正在尝试在Selenium Webdriver Python中运行脚本。 我尝试单击搜索字段的位置,但是它始终显示“使用给定的搜索参数无法在页面上找到一个元素”的例外。

这是脚本:

 from selenium import webdriver
    from selenium.webdriver.common.by import By
    class Exercise:
        def safari(self):
            class Exercise:
def safari(self):
    driver = webdriver.Safari()
    driver.maximize_window()
    url= "https://www.airbnb.com"
    driver.implicitly_wait(15)
    Title = driver.title
    driver.get(url)
    CurrentURL = driver.current_url
    print("Current URL is "+CurrentURL)
    SearchButton =driver.find_element(By.XPATH, "//*[@id='GeocompleteController-via-SearchBarV2-SearchBarV2']")
    SearchButton.click()

note= Exercise()
note.safari()

请告诉我,我哪里错了?

似乎有两种匹配的情况:

在此处输入图片说明

与搜索栏匹配的那个实际上是第二个。 因此,您可以按以下方式编辑XPath:

SearchButton = driver.find_element(By.XPATH, "(//*[@id='GeocompleteController-via-SearchBarV2-SearchBarV2'])[2]")

或者简单地:

SearchButton = driver.find_element_by_xpath("(//*[@id='GeocompleteController-via-SearchBarV2-SearchBarV2'])[2]")

您可以通过在Chrome浏览器的Inspector工具(如上所示)中粘贴XPath,方法是将相同的网站加载到Google Chrome浏览器中,然后按F12键(或右键单击任意位置,然后单击“检查”)。 这为您提供了匹配的元素。 如果滚动到2之2,则会突出显示搜索栏。 因此,我们需要第二个结果。 XPath索引从1开始,不同于大多数语言(通常具有从0开始的索引),因此要获取第二个索引,请将整个原始XPath括在括号中,然后在其旁边添加[2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM