WSJ不想被解析——我有这个功能:
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,请检查您输入的是否正确。如果您通过我们的网站或搜索到达此页面,请发送电子邮件至 [email protected] 告知我们
《华尔街日报》有它的理由,应该得到尊重——这些页面是为人类而不是机器人制作的,所以如果你表现得像一个人,那么内容对你是开放的。
user agent
已经足够了,但是如果他们检测到您的活动并将其归类为不可接受的,这可能会改变。
因此,再次尊重网站及其内容,不要轻率行动和不必要的刮擦来伤害它。
这只是为了展示技术观点,并不反映道德观点。
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"})