Hướng dẫn sử dụng XPath và xử lý popup trong Selenium

Sử dụng XPath linh hoạt để định vị phần tử

XPath là ngôn ngữ truy vấn dùng để tìm kiếm các nút trong tài liệu XML hoặc HTML. Trong Selenium, XPath có thể thay thế hoàn toàn các phương thức định vị khác nhờ khả năng biểu đạt linh hoạt:

  • find_element_by_xpath('//*[@id="kw"]') tương đương với find_element_by_id("kw")
  • find_element_by_xpath('//input[@name="search"]') tương đương với find_element_by_name("search")
  • find_element_by_xpath('//button[contains(@class, "submit")]') tương đương với find_element_by_class_name() (nếu class duy nhất)
  • find_element_by_xpath('//a[text()="Đăng nhập"]') tương đương với find_element_by_link_text()

Cú pháp cơ bản của XPath

  • Đường dẫn tuyệt đối: Bắt đầu từ gốc, ví dụ: /html/body/div[1]/form
  • Đường dẫn tương đối: Bắt đầu từ bất kỳ đâu, ví dụ: //div/form hoặc //*[@type='submit']
  • Dấu chấm (.): đại diện cho node hiện tại
  • Hai dấu chấm (..): đại diện cho node cha

Chỉ mục và thuộc tính

  • Chỉ mục bắt đầu từ 1: //div[1], //li[3]
  • Tìm theo thuộc tính: //input[@id='email']
  • Tìm theo nhiều thuộc tính: //button[@type='submit' and @class='primary']
  • Tìm theo giá trị bất kỳ: //*[@*='value']

Hàm hỗ trợ trong XPath

  • text(): lấy nội dung văn bản, ví dụ: //span[text()='Gửi']
  • contains(): kiểm tra chuỗi con, ví dụ: //a[contains(text(), 'Tài khoản')]
  • starts-with(): bắt đầu bằng, ví dụ: //label[starts-with(@for, 'user')]
  • last(): phần tử cuối cùng, ví dụ: //tr[last()]

Trục (Axes) trong XPath

  • following: các node sau, ví dụ: //*[text()='Email']/following::input[1]
  • preceding: các node trước
  • parent: node cha
  • child: node con
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://example.com/form")
driver.implicitly_wait(5)

# Tìm phần tử bằng XPath
element = driver.find_element_by_xpath("//div[@class='container']//input[@name='username']")
print(element.get_attribute("placeholder"))

Xử lý các loại hộp thoại trong Selenium

Alert thông báo

alert = driver.switch_to.alert
alert.accept()  # Nhấn OK
# hoặc alert.dismiss() để hủy (nếu có nút Hủy)

Confirm xác nhận

confirm = driver.switch_to.alert
confirm.accept()    # Xác nhận
confirm.dismiss()   # Hủy bỏ

Prompt nhập liệu

prompt = driver.switch_to.alert
prompt.send_keys("Nhập dữ liệu tại đây")
prompt.accept()     # Gửi

Xử lý modal dialog

Với modal không phải alert (thường là div overlay), chỉ cần định vị và thao tác như phần tử bình thường.

Xử lý xác thực HTTP Basic Auth

Thêm username và password trực tiếp vào URL:

driver.get("http://username:password@example.com/protected")

Làm việc với iframe và frameset

Các phần tử bên trong iframe không thể truy cập trực tiếp. Cần chuyển context sang iframe trước:

  • driver.switch_to.frame("frame_name_or_id")
  • driver.switch_to.frame(0) — chuyển sang iframe đầu tiên
  • driver.switch_to.frame(webelement) — truyền WebElement đã tìm thấy
  • driver.switch_to.parent_frame() — quay lại frame cha
  • driver.switch_to.default_content() — quay về trang chính
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://example.com/page-with-iframe")

# Chuyển vào iframe
driver.switch_to.frame("main-frame")

# Thao tác trong iframe
content = driver.find_element_by_tag_name("h2").text
print(content)

# Quay lại trang chính
driver.switch_to.default_content()

Thẻ: selenium xpath automation-testing python-selenium iframe-handling

Đăng vào ngày 7 tháng 6 lúc 03:28