I try to write a console application that simulates Google search. But trivial even I can not run almost empty code, just because of the webdriver import the console immediately closes
# -*- coding: utf-8 -*-
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
def greeting():
os.system('cls' if os.name == 'nt' else 'clear')
print('Hello')
def search():
greeting()
q = ''
while q != 'quit':
q = input()
q = q.replace(' ', '')
browser = webdriver.Firefox()
body = browser.find_elements_by_tag_name("body")
body.send_keys(Keys.CONTROL + 't')
counter = 0
for i in range(0, 20):
browser.get("https://www.google.com/search?q=" + q + "&start=" + str(counter))
body = browser.find_element_by_tag_name("body")
print(body)
counter += 10
browser.quit()
print(q)
if __name__ == '__main__':
search()
Thank you!
There are a couple of issues with your code.
The following lines:
body = browser.find_elements_by_tag_name("body")
body.send_keys(Keys.CONTROL + 't')
will not work because you are getting a list of elements (mind the s at the end of find_elements) and send_keys
will only work on a single element, also, send_keys
only works with visible elements so you cannot use the body tag.
If I comment out the problematic lines I am able to run your code but since your are calling browser.quit()
within your for loop, it will stop working after the first iteration.
Once removed, everything runs fine:
for i in range(0, 20):
browser.get("https://www.google.com/search?q=" + q + "&start=" + str(counter))
body = browser.find_element_by_tag_name("body")
print(body)
counter+=10