Web scraping tut sử dụng Selenium & Python (phần 10)

Selenium WebElement

Một WebElement trong Selenium trình bày một phần tử HTML trên một trang web. Bạn có thể thực hiện một loạt hành
động với các objects này, cái là then chốt cho tự động hóa các tương tác web và scraping dữ liệu.
Sau đây là một vài hoạt động phổ biến bạn có thể thực hiện trên một WebElement:
+ Truy cập text: Sử dụng element.text để giành text nhìn thấy được của một phần tử.
+ Clicking: Mô phỏng các clicks chuột với element.click().
+ Giành các thuộc tính: Lấy bất cứ thuộc tính nào của một phần tử sử dụng element.get_attribute(‘attribute_name’),
như element.get_attribute(‘class’).
+ Gửi các keys: Gửi text tới các trường nhập vào sử dụng element.send_keys(‘your_text’).
Một phương thức hữu dụng khác là is_displayed(), cái check liệu một phần tử có là nhìn thấy với người dùng –
hữu dụng để tránh tương tác với các phần tử ẩn có chủ đích (honeypots).

Ví dụ: rút text từ Hacker News

Để minh họa làm cách nào rút title của vật first news trên Hacker News, sau đây là một ví dụ ngắn gọn. Cấu trúc
site bao gồm một table lớn với mỗi row trình bày một news article. Phần tử td thứ ba của mối row chứa news title
và một link.

from selenium import webdriver

DRIVER_PATH = ‘/path/to/chromedriver’

# Set up Chrome WebDriver
driver = webdriver.Chrome(executable_path=DRIVER_PATH)

# Navigate to Hacker News
driver.get(“https://news.ycombinator.com/”)

# Locate the third ‘td’ of the first ‘tr’ which contains the article’s title and link
title_element = driver.find_element_by_xpath(‘//tr[@class=”athing”]/td[3]/a’)

# Extract and print the text from the located WebElement
print(title_element.text)

# Click on the link to navigate to the article’s page
title_element.click()

# Optionally, wait for the new page to load and perform actions there
# For demonstration, let’s print the current URL after clicking
print(driver.current_url)

# Close the driver
driver.quit()

Script này thiết lập một Selenium WebDriver cho Chrome, điều hướng tới Hacker News, định vị WebElement chứa
title của first news article, và in ra text của nó. Sau đó nó click lên link để ghé thăm trang tương ứng.
Ví dụ này minh họa hiệu quả làm cách nào sử dụng Selenium để scrape text từ các phần tử cụ thể trên một
webpage.

Chia sẻ