1. Intro
There are various ways to locate elements on a web page.
Selenium helps you find elements through the following methods.
• find_element_by_id()
• find_element_by_name()
• find_element_by_xpath()
• find_element_by_css_selector()
• find_element_by_link_text()
• find_element_by_partial_link_text()
• find_element_by_class_name()
• find_element_by_tag_name()
If you want to find multiple elements, you can use the following methods.
• find_elements_by_id()
• find_elements_by_name()
• find_elements_by_xpath()
• find_elements_by_css_selector()
• find_elements_by_link_text()
• find_elements_by_partial_link_text()
• find_elements_by_class_name()
• find_elements_by_tag_name()
Apart from the methods given above, there is one more method which might be useful.
driver.find_element(By.Xpath, "xpath expression")
driver.find_elements(By.Xpath, "xpath expression")
2. Practice web page
I will find elements using the Instagram web page.
URL: https://www.facebook.com/
3. Finding elements
The code for the Email field is below.
# by ID
elementById = driver.find_element(By.ID, "email")
# by Name
elementByName = driver.find_element(By.NAME, "email")
# by Xpath
elementByXpath = driver.find_element(By.XPATH, '//*[@id="email"]')
# by CSS Selector
elementByCss = driver.find_element(By.CSS_SELECTOR, "#email")
# by Link Text
elementByLinkText = driver.find_element(By.LINK_TEXT, "Forgot password")
# by Partial link text
elementByPartialLinkText = driver.find_element(By.PARTIAL_LINK_TEXT, "For")
# by class Name
elementByClassName = driver.find_element(By.CLASS_NAME, "inputtext")
# by Tag Name
elementByTagName = driver.find_element(By.TAG_NAME, "h2")
4. Practice
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
class FindByElement():
def test(self):
baseUrl = "https://www.facebook.com/"
s = Service('E:\\workspace_python\\drivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s)
driver.get(baseUrl)
elementTagName = driver.find_element(By.TAG_NAME, "h2")
text = elementTagName.text
if elementTagName is not None:
print("We found an element by Tag name and the Text is " + text)
elementByName = driver.find_element(By.NAME, "email")
elementByName.send_keys("test@test.com")
time.sleep(3)
ff = FindByElement()
ff.test()
'Testing Automation > 01. Selenium' 카테고리의 다른 글
06. Selenium | Wait ( Implicit / Explicit) (0) | 2022.03.05 |
---|---|
05. Selenium | Alert (0) | 2022.03.04 |
04. Selenium | Browser navigation (0) | 2022.03.04 |
03. Selenium | Browser control (0) | 2022.01.14 |
01. Selenium | Setting (0) | 2021.11.26 |