Thao tác với phần tử web trong Selenium

Trong Selenium, thao tác với các đối tượng kiểm thử đồng nghĩa với việc mô phỏng hành vi người dùng trên giao diện web nhằm xác minh chức năng và trải nghiệm người dùng.

1. Định vị phần tử

Selenium cung cấp nhiều cơ chế định vị phần tử như id, name, class name, CSS selector, và XPath. Hai phương thức chính được sử dụng là:

  • find_element(): trả về một phần tử duy nhất.
  • find_elements(): trả về danh sách các phần tử khớp với điều kiện.
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
element = driver.find_element(By.XPATH, "//input[@id='kw']")
elements = driver.find_elements(By.CLASS_NAME, "s_ipt")

2. Các thao tác phổ biến trên phần tử

  • .text: lấy nội dung văn bản của phần tử.
  • .send_keys(...): nhập dữ liệu vào ô input.
  • .clear(): xóa nội dung hiện có trong trường nhập liệu.
  • .click(): thực hiện hành động nhấp chuột.
  • .submit(): gửi biểu mẫu chứa phần tử đó.

Ví dụ minh họa

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

class WebInteractionDemo:
    def search_on_baidu(self, url, hot_word_xpath, search_box_xpath, 
                        first_query, second_query, search_btn_xpath):
        driver = webdriver.Chrome()
        try:
            driver.get(url)
            driver.maximize_window()

            # Lấy và in từ khóa nổi bật
            hot_word = driver.find_element(By.XPATH, hot_word_xpath).text
            print("Từ khóa nổi bật:", hot_word)

            # Nhập từ khóa đầu tiên
            search_box = driver.find_element(By.XPATH, search_box_xpath)
            search_box.send_keys(first_query)
            time.sleep(2)

            # Xóa và nhập từ khóa mới
            search_box.clear()
            search_box.send_keys(second_query)
            time.sleep(2)

            # Nhấn nút tìm kiếm
            driver.find_element(By.XPATH, search_btn_xpath).click()
            time.sleep(3)

            # Quay lại trang trước
            driver.back()
            time.sleep(2)

            # Nhập từ khóa khác và submit form
            new_search_box = driver.find_element(By.XPATH, search_box_xpath)
            new_search_box.send_keys("HelloKitty")
            new_search_box.submit()
            time.sleep(4)
        finally:
            driver.quit()

# Thực thi
demo = WebInteractionDemo()
demo.search_on_baidu(
    url="https://www.baidu.com/",
    hot_word_xpath='//*[@id="hotsearch-content-wrapper"]/li[1]/a/span[2]',
    search_box_xpath='//*[@id="kw"]',
    first_query="python",
    second_query="kiểm thử phần mềm",
    search_btn_xpath='//*[@id="su"]'
)

Thẻ: selenium webdriver python xpath CSS Selector

Đăng vào ngày 14 tháng 8 lúc 14:19