Selenium href 循环未完成
我在这个问题上卡了好几周,找了很多地方想要解决它。我想从某个体育网站上抓取一些信息。我能获取到框框的标题,还有下面的小描述,但当我尝试获取 href
时,循环就中途停止了,并且出现了一个错误。
error(selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":".//a"}).
这是我一直在运行的代码。起初我以为是找元素的问题,直到我加了打印语句(print(link)),因为我只得到了第一个链接或者直接是错误。我尝试过用不同的方法来找到它,比如用xpath、css选择器或者标签等等,但都没有成功。
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
website = 'https://www.thesun.co.uk/sport/football/'
path = 'D:\\Programming\\Automate with Python\\Automating\\chromedriver_win32'
chrome_options = Options()
chrome_options.add_experimental_option('detach', True)
service = Service(executable_path=path)
browser = webdriver.Chrome(options=chrome_options)
browser.get(website)
containers = browser.find_elements(by="xpath", value='//div[@class="teaser__copy-container"]')
titles = []
sub_titles = []
links = []
for container in containers:
title = container.find_element(By.CSS_SELECTOR, 'span').get_attribute("textContent")
sub_title = container.find_element(By.CSS_SELECTOR, 'h3').get_attribute("textContent")
link = container.find_element(By.XPATH, './/a').get_attribute("href")
titles.append(title)
sub_titles.append(sub_title)
links.append(link)
print(link)
df_headlines = pd.DataFrame({'title': titles, 'sub-title': sub_titles, 'links': links})
df_headlines.to_csv('headline.csv')
这可能是网站上的一个坏链接吗?如果有人能帮忙,我会非常感激,因为这对我来说有点挑战,我想解决这个问题,提前谢谢大家。
1 个回答
0
这个问题出现是因为其中一个容器里没有“a”元素。你可以在开发者工具的控制台查看。
$x("//div[@class='teaser__copy-container']")
执行这个代码会返回68个元素,
$x("//div[@class='teaser__copy-container']//a")
而这个代码只返回67个。
要知道哪个元素是$x("//div[@class='teaser__copy-container'
但没有.//a)]
的。
正如我之前说的,修改这一行代码。这会强制容器里面有“a”元素。或者你可以用try-except来查找元素,并设置默认值为空链接。
containers = browser.find_elements(by="xpath", value='//div[@class="teaser__copy-container" and .//a]')