In order to interact with a web page in Selenium you have to locate the element. As a human you do this without much thought. In Selenium it requires more thought (sadly).
There are lots of ways to find elements on a page. The most specific way is by id. Meaning there is an element on a page and it has a unique id on it. If you looked at the HTML source a unique id would look like this:
<button id="mybutton">click me</button>
When you have a button that has an id on it then you can locate it in Python like this
e = driver.find_element_by_id("mybutton")
Another way to do the exact same thing as above but the code is slightly different.
from selenium.webdriver.common.by import By # note 1
e = driver.find_element(By.ID,"mybutton")
Note 1 - you need another import for this code to work.
If you want to use an XPath locator the code will look like this
driver.find_element(By.XPATH, '//button[text()="click me"]')
There is also a way to find multiple elements that match the same locator by using the find_elements method instead of find_element.
See here for lots more information and all of the other locator types: https://selenium-python.readthedocs.io/locating-elements.html
Top comments (0)