通过任务练习连接到页面并从中获取信息



我现在正在处理这项任务:"使用BeautifulSoup并请求Python包在《纽约时报》主页上打印出所有文章标题的列表"现在我只能连接到页面:

import requests
from bs4 import BeautifulSoup
r = requests.get("https://www.nytimes.com/")
if r.status_code == 200:
print("Page opened successfully.")
soup = BeautifulSoup(r.text,'html.parser')
else:
print("Page not found!")
exit(1)
r_html = r.text
exit(0)

所以。。。我的问题是如何使用";bs4";库和源代码从页面中找到我想要的信息(主页上的文章列表(?

排序标准(文章的常见标签或html属性(是主要的挑战。我在下面所做的是抓取标签中出现的所有文章标题。

import requests
from bs4 import BeautifulSoup
r = requests.get("https://www.nytimes.com/")
if r.status_code == 200:
print("Page opened successfully.")
soup = BeautifulSoup(r.text,'html.parser')
result = soup.find_all('h2')
headlines = []
for i in result:
if result.index(i) < len(result)-2:
headlines.append(i.text)
else:
print("Page not found!")
exit(1)
r_html = r.text
print(headlines)
exit(0)

您可能需要一些时间来研究页面来源,因为这将使您更深入地了解文章标题的独特属性(使用可以更好地抓取您想要的信息(

最新更新