如何用请求和 BeautifulSoup 抓取《华尔街日报》的头条新闻?

How to scrape WSJ headlines with requests and BeautifulSoup?

提问人:miraculous_guru 提问时间:4/1/2023 最后编辑:HedgeHogmiraculous_guru 更新时间:4/1/2023 访问量:90

问:

华尔街日报不想被解析 - 我有这个函数:

def get_wsj_news():
    global prev_news_wsj
    url = "https://www.wsj.com/news/world"
    news = []
    news_to_post = []
    try:
        response = requests.get(url)
        soup = BeautifulSoup(response.content, "html.parser")
        news_list = soup.find_all("h3", {"class": "WSJTheme--headline--unZqjb45"})
        for item in news_list[:15]:
            headline = item.text.strip()
            news.append(f"• {headline}")
            news_to_post.append(f"• <b>{headline}</b>")
        if not news or news == prev_news_wsj:
            return {"site": None, "message": None}
        else:
            prev_news_wsj = news
            print(url)
            return {"site": "The Wall Street Journal", "message": "\n".join(news_to_post)}
    except Exception as e:
        print(e)

但是当我尝试解析标签时,我看到以下内容:<h3>

我们找不到您要查找的页面。如果您在浏览器中键入了 URL,请检查您输入的 URL 是否正确。如果您通过我们的网站或搜索访问此页面,请发送电子邮件至 [email protected] 告知我们。

python 网页抓取 beautifulsoup python请求 html 解析

评论


答:

1赞 HedgeHog 4/1/2023 #1

《华尔街日报》有其理由,应该得到尊重——这些页面是为人类而不是机器人制作的,所以如果你表现得像人,内容对你开放。


在这种情况下,在请求中使用用户代理就足够了,但如果他们检测到您的活动并将其归类为不允许,这可能会发生变化

因此,请再次尊重网站及其内容,不要通过轻率的行动和不必要的抓取来伤害它。

这只是为了显示技术观点,并不反映道德观点。

import requests
from bs4 import BeautifulSoup

url = "https://www.wsj.com/news/world"
response = requests.get(url, headers={'user-agent':'some agent'})
soup = BeautifulSoup(response.content, "html.parser")
soup.find_all("h3", {"class": "WSJTheme--headline--unZqjb45"})