我在使用 Selenium 从 The Sun Football 网站抓取新闻标题、字幕和链接时遇到了挑战。尽管实现了看似正确的 XPath 来针对容器所需的元素
(div[@class="teaser__copy-container"]
、标题的 span[@class="teaser__headline teaser__kicker t-p-color"]
和字幕的 h3[@class="teaser__subdeck"]
),但我始终为所有新闻项提取相同的数据。
代码片段
from selenium import webdriver
from selenium.webdriver.firefox.service import Service # Using Firefox service
import pandas as pd
# Website URL for news scraping
website = "https://www.thesun.co.uk/sport/football/"
# Path to the GeckoDriver executable
path = "/Users/dada/AutomationProjects/drivers/geckodriver.exe"
# Configure Firefox service with GeckoDriver path
service = Service(executable_path=path)
# Initialise Firefox WebDriver using the service
driver = webdriver.Firefox(service=service)
# Open the desired website
driver.get(website)
containers = driver.find_elements(by="xpath", value='//div[@class="teaser__copy-container"]')
titles = []
subtitles = []
links = []
for container in containers:
title = container.find_element(by="xpath", value='//div[@class="teaser__copy-container"]/a/span[@class="teaser__headline teaser__kicker t-p-color"]').get_attribute("data-original-text")
subtitle = container.find_element(by="xpath", value='//div[@class="teaser__copy-container"]/a/h3[@class="teaser__subdeck"]').get_attribute("data-original-text")
link = container.find_element(by="xpath", value='//div[@class="teaser__copy-container"]/a').get_attribute("href")
titles.append(title)
subtitles.append(subtitle)
links.append(link)
dict = {'Titles' : titles, 'Subtitles' : subtitles, 'Links' : links}
headlines_df = pd.DataFrame(dict)
print(headlines_df)
已验证的 XPath:我使用浏览器开发人员工具仔细检查了 XPath,以确保它们准确地定位预期元素。 问题仍然存在。尽管执行了故障排除步骤,我仍然提取相同的标题、副标题和链接。
硒版本:4.19.0 | Python 版本:3.9.19 |环境:Jupyter笔记本
如果有任何见解或建议可以帮助我确定此问题的根本原因,并成功从《太阳足球》网站上抓取不同的标题、字幕和链接,我将不胜感激。
是的...所以当您从现有元素搜索时,您必须使用 XPath 做一些“奇怪”的事情。而不是
link = container.find_element(By.XPATH, '//div[@class="teaser__copy-container"]/a')
您需要添加一个“.”到 XPath 的开头,例如
link = container.find_element(By.XPATH, './/div[@class="teaser__copy-container"]/a')
^ period added here
这只适用于 XPath,并且仅当您在元素中使用
.find_element()
时。这应该可以解决您的问题。
其他反馈
从 Selenium 4.6 开始,您不再需要下载、配置和维护自己的驱动程序。添加了Selenium Manager,它将自动下载并设置与您安装的浏览器匹配的驱动程序。因此,您的初始代码可以简化为
from selenium import webdriver
website = "https://www.thesun.co.uk/sport/football/"
driver = webdriver.Firefox()
driver.get(website)
编写.find_element()
调用的
首选方式是
from selenium.webdriver.common.by import By
driver.find_element(By.XPATH, '//div[@class="teaser__copy-container"]/a')
您的方法可行,但很容易出现拼写错误,并且您的 IDE 不会知道拼写错误,直到您运行脚本并且脚本失败。使用
By.XPATH
等可以避免定位器类型中的拼写错误,并且您的 IDE 将帮助您自动完成它。如果存在拼写错误,IDE 会在运行之前将其标记为错误,从而节省您的时间。