无法在selenium Webdriver python中通过XPath选择元素

无法在selenium Webdriver python中通过XPath选择元素,python,selenium,xpath,selenium-webdriver,Python,Selenium,Xpath,Selenium Webdriver,我正在尝试用SeleniumWebDriverPython运行一个脚本。我试图点击搜索字段,但它总是显示一个元素的异常,无法使用给定的搜索参数在页面上找到 下面是脚本: from selenium import webdriver from selenium.webdriver.common.by import By class Exercise: def safari(self): class Exercise: def safari(

我正在尝试用SeleniumWebDriverPython运行一个脚本。我试图点击搜索字段,但它总是显示一个元素的异常,无法使用给定的搜索参数在页面上找到

下面是脚本:

 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]")

您可以将XPath粘贴到Chrome的Inspector工具中,如上所示,方法是在Google Chrome中加载相同的网站并点击F12,或者右键单击任意位置并单击Inspect。这将为您提供匹配的元素。如果滚动至2/2,则会突出显示搜索栏。因此,我们想要第二个结果。XPath索引从1开始,这与大多数语言的索引通常从0开始不同,因此要获得第二个索引,请将整个原始XPath封装在括号中,然后在其旁边添加[2]

事实上,我之前在尝试处理类,我已经更新了代码。请现在检查。整个脚本已运行,意味着浏览器已打开,站点已执行,我已获得当前URL,但未获得单击。@TaimoorPasha有两个相同id的输入。第二个是显示的内容。将xpath切换到-//main[@id='site-content']//input[@id='geopletecontroller-via-SearchBarV2-SearchBarV2']@Grasshopper我尝试过使用您提供的xpath,但仍然不起作用。@Grasshopper还告诉我,这是我可以检查我创建的XPath是否正确的任何方法。实际上,我之前尝试使用类,我已经更新了代码。请现在检查更新了我的答案@TaimoorPashaThanks Mangohero1,这真是太棒了,你能教我如何使用xpath吗?当然@TaimoorPasha我已经包含了一些关于太大而无法作为评论的解释请将你的skype id或电子邮件地址发送到taimoorpasha2009@gmail.com