Selenium provides an excellent surfing of the browser automatically. Below is the codes which I suggested my reader to login to his desired website. In this article, I’m using that very website as an example.
Selenium Python Example to login to a website
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time browser = webdriver.Firefox() browser.get("https://lbjcrs.ust.hk/primo/authen.php") time.sleep(10) username = browser.find_element_by_id("extpatid") password = browser.find_element_by_id("extpatpw") username.send_keys("username") password.send_keys("password") login_attempt = browser.find_element_by_xpath("//*[@type='submit']") login_attempt.submit()
Explanation of python codes to login to website using selenium
1. Line 1 to 3
2. Line 4 to 6
In line 4, we instantiate a Firefox webbrowser. This line will open a browser.
3. Line 7 to 10
For placing the username and password to the appropriate fields, we need a prior knowledge of the input field. Right click on the field and click on inspect element to reveal it’s id. Once we have the id for both username and password fields, we can proceed to programatically adding the values to these fields. In line 7 and 8, we’re assigning variables to hold the fields(username and password). In line 9 and 10, we’re using the methods send_keys over these fields to pass the username and passwords respectively. By the end of line 10 the username and password will be already set in the browser.
4. Line 11
In line 11, we’re using the find_element_by_xpath to find a submit button on the webpage being displayed in the webbrowser. We assign this find to login_attempt.
5. Line 12
Finally, we trigger a click event on the submit button which will then login to the website for us.