【发布时间】:2023-03-12 05:35:01
【问题描述】:
我正在尝试学习如何使用 Python 抓取新闻标题,并阅读我发现的这篇文章:https://medium.com/analytics-vidhya/how-to-scrape-news-headlines-from-reuters-27c0274dc13c
它工作得很好,但是当我尝试用其他新闻页面模拟它时,我继续得到没有这样的元素错误。我意识到这是因为我在 html 中选择了错误的类元素,但是我不明白我应该选择什么其他类。
本新闻页面使用了以上脚本:https://www.reuters.com/news/archive/technologynews?view=page&page=6&pageSize=10
我试图在以下页面上使用它,特别是调查当地的国家机构:
https://www.startribune.com/search/?page=1&q=%22Department%20of%20Human%20Services%22&refresh=true
https://www.twincities.com/?s=%22Department+of+Human+Services%22&orderby=date&order=desc
这是代码,其中唯一的变化是用我正在研究的第一个网页替换路透社网页,并替换按钮选择的类元素:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import dateutil.parser
import time
import csv
from datetime import datetime
import io
driver = webdriver.Chrome('chromedriver.exe')
driver.get('https://www.startribune.com/search/?page=1&q=%22Department%20of%20Human%20Services%22&refresh=true')
count = 0
headlines =[]
dates = []
for x in range(500):
try:
# loadMoreButton.click()
# time.sleep(3)
loadMoreButton = driver.find_element_by_class_name("pagination-shortcut-link")
# driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(3)
loadMoreButton.click()
time.sleep(2)
news_headlines = driver.find_elements_by_class_name("story-title")
news_dates = driver.find_elements_by_class_name("timestamp")
for headline in news_headlines:
headlines.append(headline.text)
print(headline.text)
for date in news_dates:
dates.append(date.text)
print(date.text)
count=count+1
print("CLICKED!!:")
except Exception as e:
print(e)
break
为了获得类名,我右键单击下一步按钮并选择检查元素并复制我看到的内容。但是我继续收到错误。我不确定我打算使用什么其他类元素。
【问题讨论】:
-
如果一个选择器不适合您,也许可以尝试使用另一个(XPath、标签名称等)
-
我对这一切都很陌生,所以我不太确定你的意思。我应该阅读 find_element_by_class_name 函数的文档吗?你知道有哪些页面详细介绍了你提到的内容吗?
标签: python selenium xpath css-selectors webdriverwait