Selenium Browser Automation

Documentation

  1. Website.
  2. Selenium documentation.
  3. Selenium IDE documentation.
  4. Wikipedia.

Installation

pip3 search selenium
pip3 install selenium
pip3 list

pip3 show selenium
Name: selenium
Version: 3.141.0
Summary: Python bindings for Selenium
Home-page: https://github.com/SeleniumHQ/selenium/
Author: UNKNOWN
Author-email: UNKNOWN
License: Apache 2.0
Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
Requires: urllib3
Required-by:

pip3 show --files selenium | cat -n

Find out what version of Chrome you have by pulling down
Chrome → About Google Chrome
Then go here and download the appropriate version of chromedriver. I left it in my Mac’s Downloads directory.

Open a browser window and type

I pointed my Chrome browser at https://www.google.com/ and pulled down
View → Developer → Inspect Elements
Then I hovered over the input element (the rectangle where you type your query) and discovered that its name attribute was q.

"""
Open a browser window, type something, and examine the results.
Change myname to yourname.
"""

import sys
import re
import time
import selenium.webdriver

driver = selenium.webdriver.Chrome("/Users/myname/Downloads/chromedriver")

url = "http://www.google.com/"
driver.get(url)
time.sleep(5)   #seconds
driver.maximize_window()

query = driver.find_element_by_name("q")
query.send_keys("WS19PB02" + selenium.webdriver.common.keys.Keys.ENTER)   #or RETURN

time.sleep(5)
driver.refresh()
time.sleep(5)

html = driver.page_source
if re.search(r'<div id="resultStats">(About )?[\d,]+ results?<nobr> \(\d+(\.\d+)? seconds?\)&nbsp;</nobr></div>', html):
    print("found")
else:
    print("not found")

driver.quit()   #Close the browser window.
sys.exit(0)
The Google results page for WS19PB02 contained the following HTML, which matched the regular expression.
<div id="resultStats">4 results<nobr> (0.26 seconds)&nbsp;</nobr></div>
found