简体   繁体   中英

Unable to select an element via XPath in selenium Webdriver python

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?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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