以下是使用Python中的requests库和beautifulsoup库获取新闻标题的示例代码:

import requests
from bs4 import BeautifulSoup

url = 'https://www.bbc.com/news'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

news_titles = []

for title in soup.find_all('h3', class_='gs-c-promo-heading__title gel-paragon-bold nw-o-link-split__text'):
    news_titles.append(title.text.strip())

print(news_titles)

解释一下代码逻辑:

首先,我们定义了一个URL变量,指向BBC新闻网站的首页。然后,使用requests库发送一个GET请求,获取网页的HTML代码。接下来,我们使用beautifulsoup库将HTML代码解析为BeautifulSoup对象,以便于我们对网页进行操作。

在这个例子中,我们想要获取新闻标题,因此我们使用find_all()方法找到所有class属性为'gs-c-promo-heading__title gel-paragon-bold nw-o-link-split__text'的

标签。然后,我们使用循环,将每个标题的文本内容添加到news_titles列表中。

最后,我们将新闻标题打印出来。

请注意,我们使用strip()方法去除标题中的空格和换行符

使用requests库和beautifulsoup获取新闻标题


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

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