[英]Unable to select an element via XPath in selenium Webdriver python
I am trying to run a script in selenium webdriver python. 我正在尝试在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? 请告诉我,我哪里错了?
There appears to be two matching cases: 似乎有两种匹配的情况:
The one that matches the search bar is actually the second one. 与搜索栏匹配的那个实际上是第二个。 So you'd edit your XPath as follows:
因此,您可以按以下方式编辑XPath:
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"). 您可以通过在Chrome浏览器的Inspector工具(如上所示)中粘贴XPath,方法是将相同的网站加载到Google Chrome浏览器中,然后按F12键(或右键单击任意位置,然后单击“检查”)。 This gives you the matching elements.
这为您提供了匹配的元素。 If you scroll to 2 of 2 it highlights the search bar.
如果滚动到2之2,则会突出显示搜索栏。 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. XPath索引从1开始,不同于大多数语言(通常具有从0开始的索引),因此要获取第二个索引,请将整个原始XPath括在括号中,然后在其旁边添加
[2]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.