无法在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()

请告诉我,我哪里错了?

I am trying to run a script in selenium webdriver python. Where I am trying to click on search field, but its always showing exception of "An element could not be located on the page using the given search parameters."

Here is script:

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()

Please Tell me, where I am wrong?

最满意答案

似乎有两个匹配的情况:

在这里输入图像描述

与搜索栏匹配的那个实际上是第二个。 因此,您可以按如下方式编辑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]")

您可以通过在谷歌浏览器中加载同一网站并点击F12(或者在任何地方点击鼠标右键并点击“检查”),将您的XPath粘贴到Chrome的Inspector工具中(如上所示)。 这给你匹配的元素。 如果您滚动到2中的2,则会突出显示搜索栏。 因此,我们想要第二个结果。 与大多数语言(通常索引从0开始)不同,XPath索引从1开始,因此要获得第二个索引,请将整个原始XPath封装在括号内,然后在其旁边添加[2] 。

There appears to be two matching cases:

enter image description here

The one that matches the search bar is actually the second one. So you'd edit your XPath as follows:

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

Or simply:

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

You can paste your XPath in Chrome's Inspector tool (as seen above) by loading the same website in Google Chrome and hitting F12 (or just right click anywhere and click "Inspect"). This gives you the matching elements. If you scroll to 2 of 2 it highlights the search bar. Therefore, we want the second result. XPath indices start at 1 unlike most languages (which usually have indices start at 0), so to get the second index, encapsulate the entire original XPath in parentheses and then add [2] next to it.

更多推荐