Inputting data in Google Search using Selenium
Hello all, in this article, we will focus on the use of Selenium in searching for any word.
Let us begin:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
2. Now loading the chromedriver.exe so as to automate chrome. Remember: Different browser has their unique driver.
driver = webdriver.Chrome("chromedriver.exe")
3. Assigning our target link to the driver
driver.get("https:\\www.google.co.in")
4. Now extracting the XPath of the input field in google:
And assign it to a variable in which the element of the input field will be located
box = driver.find_element_by_xpath("/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input")
We can see the content in the double inverted quotes. Now to make it easy to understand we can modify it. here everything is a part of HTML form so "/html/body -> //" and since the number of "div" in the code can be changed in the future (It can never be the same) so we put "*" asterisk in between 2 HTML elements. In this case, it's "between body and form" so any number of div will come in asterisk as the "form" will not change. Therefore, the modified code is:
box = driver.find_element_by_xpath("https://*/form/div[1]/div[1]/div[1]/div/div[2]/input")
5. We can see the input element by printing it:
print("The input Element is: ", box)
6. Now we send our "Search Text" to the input field. "send_keys" function is used to send search text:
box.send_keys("Python")
7. Now in place of extracting the element of the Search button (That will ofcourse extend the time and space complexity) we simply write code to hit on entering button in the input field)
box.send_keys(Keys.RETURN)
8. Finally we put a sleep of 5 seconds to see our search result to arrive and close the driver.
time.sleep(5)
driver.close()
Our Complete Code Looks like this:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome("chromedriver.exe")
driver.get("https:\\www.google.co.in")
box = driver.find_element_by_xpath("https://*/form/div[1]/div[1]/div[1]/div/div[2]/input")
print("The input Element is: ", box)
box.send_keys("Send")
box.send_keys(Keys.RETURN)
time.sleep(5)
driver.close()
Output:
We can see the Input element here:
Hope you all find the Content useful :)