以下是使用 Requests 库和 BeautifulSoup 获取新闻标题的示例代码:

import requests
from bs4 import BeautifulSoup

url = 'https://news.google.com/topstories?hl=en-US&gl=US&ceid=US:en'
response = requests.get(url)

soup = BeautifulSoup(response.content, 'html.parser')

news_titles = soup.find_all('a', class_='DY5T1d')

for title in news_titles:
    print(title.text)

解释:

  1. 首先,我们使用 Requests 库发送 GET 请求以获取页面的 HTML 内容。
  2. 然后,我们使用 BeautifulSoup 库将 HTML 内容解析为 BeautifulSoup 对象。
  3. 接下来,我们使用 soup.find_all() 方法查找所有包含新闻标题的 a 标签元素,并返回它们的列表。
  4. 最后,我们使用 for 循环遍历新闻标题列表,并打印每个标题的文本内容。
Python 抓取新闻标题:使用 Requests 和 BeautifulSoup

原文地址: https://www.cveoy.top/t/topic/oBrq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录