Taimoor Pasha
Taimoor Pasha

Reputation: 310

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?

Upvotes: 0

Views: 914

Answers (1)

Mangohero1
Mangohero1

Reputation: 1912

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.

Upvotes: 1

Related Questions