Mhyles
Mhyles

Reputation: 21

Getting search bar ID for selenium

Trying to get the search bar ID from this website: http://www.pexels.com

browser = webdriver.Chrome(executable_path="C:\\Users\\James\\Documents\\PythonScripts\\chromedriver.exe")
url = "https://www.pexels.com"
browser.get(url)
browser.maximize_window()


search_bar = browser.find_element_by_id("//input[@id='search__input']")
search_bar.send_keys("sky")
search_button.click()

However this isn't correct and I'm not sure how to get the search to work. First time using selenium so all help is appreciated!

Upvotes: 2

Views: 12758

Answers (2)

Tom
Tom

Reputation: 2661

Locating Elements gives an explanation on how to locate elements with Selenium.

The element you want to select, looks like this in the DOM:

<input required="required" autofocus="" class="search__input" type="search" placeholder="Search for free photos…" name="s"> 

Since there is no id specified you can't use find_element_by_id.

For me this worked:

search_bar = driver.find_element_by_xpath('/html/body/header[2]/div/section/form/input')
search_bar.send_keys("sky")
search_bar.send_keys(Keys.RETURN)

for the selection you can also use the class name:

search_bar = driver.find_element_by_class_name("search__input")

or the name tag:

search_bar = driver.find_element_by_name('s')

However, locating elements by names is probably not a good idea if there are more elements with the same name (link)

BTW if you are unsure about the xpath, the google Chrome inspection tool lets you copy the xpath from the document: enter image description here

Upvotes: 2

optimistic_creeper
optimistic_creeper

Reputation: 2799

There's no id attribute in the tag you are searching for. You may use css selectors instead. Here's a sample snippet:

search_bar = driver.find_element_by_css_selector("input[placeholder='Search for free photos…']");
search_bar.send_keys("sky")
search_bar.send_keys(Keys.RETURN)

Above snippet will insert 'sky' in the search bar and hit enter button.

Upvotes: 4

Related Questions