使用Selenium抓取《太阳报》足球板块重复数据问题求助
问题根源与解决方案
核心问题原因
你抓取到重复数据的关键问题在于循环内的XPath定位逻辑错误:当你在container.find_element()中使用以//开头的XPath时,Selenium会从整个HTML文档的根节点开始查找元素,而非从当前遍历的container元素下进行相对查找。这就导致每次循环都只会抓取页面上第一个匹配的标题、副标题和链接,最终所有条目都是重复内容。
修正代码
将循环内的XPath改为相对路径,以.开头表示从当前container元素下开始查找,或者直接定位子元素:
from selenium import webdriver from selenium.webdriver.firefox.service import Service import pandas as pd website = "https://www.thesun.co.uk/sport/football/" path = "/Users/dada/AutomationProjects/drivers/geckodriver.exe" service = Service(executable_path=path) driver = webdriver.Firefox(service=service) driver.get(website) containers = driver.find_elements(by="xpath", value='//div[@class="teaser__copy-container"]') titles = [] subtitles = [] links = [] for container in containers: # 基于当前container元素的相对路径定位 a_tag = container.find_element(by="xpath", value='./a') title = a_tag.find_element(by="xpath", value='./span[@class="teaser__headline teaser__kicker t-p-color"]').get_attribute("data-original-text") subtitle = a_tag.find_element(by="xpath", value='./h3[@class="teaser__subdeck"]').get_attribute("data-original-text") link = a_tag.get_attribute("href") titles.append(title) subtitles.append(subtitle) links.append(link) news_dict = {'Titles' : titles, 'Subtitles' : subtitles, 'Links' : links} headlines_df = pd.DataFrame(news_dict) print(headlines_df) driver.quit()
额外优化建议
- 添加显式等待:避免页面未完全加载就开始抓取,防止元素找不到的异常:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # 打开页面后等待目标容器加载完成 wait = WebDriverWait(driver, 10) containers = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="teaser__copy-container"]')))
- 处理元素缺失情况:部分新闻可能没有副标题,建议增加异常处理避免程序崩溃:
for container in containers: a_tag = container.find_element(by="xpath", value='./a') title = a_tag.find_element(by="xpath", value='./span[@class="teaser__headline teaser__kicker t-p-color"]').get_attribute("data-original-text") # 副标题可能不存在,用find_elements判断 subtitle_elems = a_tag.find_elements(by="xpath", value='./h3[@class="teaser__subdeck"]') subtitle = subtitle_elems[0].get_attribute("data-original-text") if subtitle_elems else "无副标题" link = a_tag.get_attribute("href") titles.append(title) subtitles.append(subtitle) links.append(link)
内容的提问来源于stack exchange,提问作者Darry Mich
相关产品推荐
相关产品推荐

