Controlling a Browser From Python

Recently, I had a teacher complain about not receiving any nice emails. She would only be emailed about poor grades and students whining about their tests. Thus, I decided I would send her a nice email everyday, but of course I did not want to do this by hand. So I quickly learned about an library in Python called Selenium, and figured out how to use it to control my web browser.
So for this project, I needed my computer to open a web browser, go to a URL, log into my school account, and then select the recipient along with randomly filling the body with positive information. To email her, I had to use Canvas, the software my school uses for online activities, and sign into my account. To begin I needed install the chrome driver to the folder that the python file was in, and then added this code to import the Selenium library into my project:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from pynput.keyboard import Key, Controller
Along with this I imported a library called PynPut, which allowed me to use the code to send keyboard inputs. After importing the library, to create the browser server needed to open the chrome browser.
browser = webdriver.Chrome(executable_path=r"Path to the drivers")
After setting this up, you can fullscreen the browser with:
browser.maximize_window()
And then input a URL using:
browser.get('Your URL')
Now that we’ve reached a webpage, we need to input and maneuver around the site. The best way I found of doing this, is by opening the HTML of the site (f12), and copying the xPaths of the elements on the page you need to change. Then, in the code you need to create an element, which you can then use certain commands alongside:
element = browser.find_element_by_xpath('Your Elements xPath').click()
element = browser.find_element_by_xpath('Your Elements xPath').send_keys("String to Input")
.click() Allows you to click on an element on the page.
.send_keys() Allows you to input a string into an input block.
Then at the end of the task, you can use:
browser.quit()
To close the entire browser and quit the process. This then allows you to put the entire script into a loop, if you’re looking to fill something out infinitely, or you could run it as a bat file with the scheduler as I explained in my text message bot tutorial.
Now, have fun filling out forms, and robotically controlling your browser.