要使用 python 讀取網(wǎng)頁(yè)元素,請(qǐng)按照以下步驟操作:導(dǎo)入 selenium 庫(kù)中的 webdriver。啟動(dòng)瀏覽器,例如 chrome 驅(qū)動(dòng)程序。使用 find_element_by_* 方法查找網(wǎng)頁(yè)元素。使用 element.text 讀取元素文本。使用 element.get_attribute() 讀取元素屬性。使用 element.location 和 element.size 讀取元素位置和大小。
網(wǎng)頁(yè)元素讀取指南
網(wǎng)頁(yè)元素讀取是網(wǎng)站自動(dòng)化和數(shù)據(jù)提取的關(guān)鍵任務(wù)。本文將指導(dǎo)你如何使用 Python 和 Selenium 讀取網(wǎng)頁(yè)元素的文本、屬性和位置。
導(dǎo)入必要的庫(kù)
from selenium import webdriver
登錄后復(fù)制
啟動(dòng)瀏覽器
driver = webdriver.Chrome() # 或其他瀏覽器驅(qū)動(dòng)程序
登錄后復(fù)制
查找網(wǎng)頁(yè)元素
使用 Selenium 的 find_element_by_*
方法查找元素:
find_element_by_id("my_id")
find_element_by_name("my_name")
find_element_by_class_name("my_class")
find_element_by_xpath("//element/path")
讀取元素文本
text = element.text
登錄后復(fù)制
讀取元素屬性
value = element.get_attribute("attribute_name")
登錄后復(fù)制
讀取元素位置
location = element.location # 返回 {x, y} 坐標(biāo) size = element.size # 返回 {width, height}
登錄后復(fù)制
實(shí)戰(zhàn)案例
從 IMDb 網(wǎng)站提取電影標(biāo)題和評(píng)分:
# 打開(kāi) IMDb 網(wǎng)站 driver.get("https://www.imdb.com/") # 獲取前 10 部電影的標(biāo)題和評(píng)分 titles = [] ratings = [] for i in range(1, 11): # 查找標(biāo)題元素 title_element = driver.find_element_by_xpath(f"(//h3)[{i}]/a") # 讀標(biāo)題 title = title_element.text # 查找評(píng)分元素 rating_element = driver.find_element_by_xpath(f"(//strong)[{i}]") # 讀評(píng)分 rating = rating_element.text titles.append(title) ratings.append(rating) # 打印結(jié)果 for title, rating in zip(titles, ratings): print(f"{title}: {rating}")
登錄后復(fù)制
這將打印類(lèi)似于以下內(nèi)容的結(jié)果:
The Shawshank Redemption: 9.3 The Godfather: 9.2 The Dark Knight: 9.0 Schindler's List: 9.0 12 Angry Men: 9.0 ...
登錄后復(fù)制