Tám Phương Pháp Định Vị Phần Tử Trong Selenium

Khái niệm định vị phần tử

Định vị phần tử là quá trình xác định các thành phần giao diện web để tương tác trong tự động hóa. Trang web được cấu trúc từ các thẻ HTML lồng ghép, có thể quan sát qua công cụ Developer Tools (F12).

Định vị bằng ID

Sử dụng thuộc tính ID duy nhất của thẻ HTML:

from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep

trinh_duyet = webdriver.Chrome()
trinh_duyet.get("https://www.bing.com")
sleep(1)
trinh_duyet.find_element(By.ID, 'sb_form_q').send_keys('automation')
sleep(2)
trinh_duyet.quit()

Định vị bằng NAME

Nhận diện phần tử thông qua thuộc tính name:

trinh_duyet = webdriver.Chrome()
trinh_duyet.get("https://www.bing.com")
sleep(1)
trinh_duyet.find_element(By.NAME, 'q').send_keys('selenium')
sleep(2)
trinh_duyet.quit()

Định vị bằng CLASS_NAME

Sử dụng giá trị class của phần tử (lưu ý class có thể không duy nhất):

trinh_duyet = webdriver.Chrome()
trinh_duyet.get("https://www.bing.com")
sleep(1)
trinh_duyet.find_element(By.CLASS_NAME, 'sb_form_q').send_keys('testing')
sleep(2)
trinh_duyet.quit()

Định vị bằng TAG_NAME

Xác định phần tử qua tên thẻ HTML (thường trả về nhiều kết quả):

trinh_duyet = webdriver.Chrome()
trinh_duyet.get("https://example.com")
trinh_duyet.maximize_window()
cac_phantu = trinh_duyet.find_elements(By.TAG_NAME, "input")
cac_phantu[0].send_keys("data")
trinh_duyet.quit()

Định vị bằng LINK_TEXT

Tìm liên kết theo nội dung văn bản đầy đủ:

trinh_duyet = webdriver.Chrome()
trinh_duyet.get("https://example.com")
trinh_duyet.find_element(By.LINK_TEXT, "Information").click()
sleep(1)
trinh_duyet.quit()

Định vị bằng PARTIAL_LINK_TEXT

Tìm liên kết theo đoạn văn bản con:

trinh_duyet = webdriver.Chrome()
trinh_duyet.get("https://example.com")
trinh_duyet.find_element(By.PARTIAL_LINK_TEXT, "Info").click()
sleep(1)
trinh_duyet.quit()

Định vị bằng XPath

Cú pháp XPath cho đường dẫn tuyệt đối:

trinh_duyet = webdriver.Chrome()
trinh_duyet.get("https://example.com")
duong_dan = '/html/body/div/div[1]/form/input[1]'
trinh_duyet.find_element(By.XPATH, duong_dan).send_keys("text")
trinh_duyet.quit()

Cú pháp XPath tương đối với thuộc tính:

trinh_duyet.find_element(By.XPATH, '//input[@id="search"]').send_keys("query")
trinh_duyet.find_element(By.XPATH, '//button[@type="submit"]').click()

Định vị bằng CSS Selector

Sử dụng bộ chọn CSS với các quy tắc:

trinh_duyet = webdriver.Chrome()
trinh_duyet.get("https://example.com")
trinh_duyet.find_element(By.CSS_SELECTOR, '#searchField').send_keys("css")
trinh_duyet.find_element(By.CSS_SELECTOR, '.submit-btn').click()
sleep(1)
trinh_duyet.quit()

Thẻ: selenium WebAutomation ElementLocation xpath CSS_Selector

Đăng vào ngày 30 tháng 6 lúc 08:19