Python爬虫实战:使用Requests和BeautifulSoup获取新闻标题
下面是使用requests库和beautifulsoup获取新闻标题的示例代码:
import requests
from bs4 import BeautifulSoup
url = 'https://news.baidu.com/'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
news_titles = soup.find_all('a', {'class': 'title-link'})
for title in news_titles:
print(title.get_text())
首先,我们使用requests库发送GET请求获取新闻页面的HTML代码。然后,使用BeautifulSoup库将HTML代码解析为BeautifulSoup对象。接着,使用find_all()方法查找所有class属性为'title-link'的标签,并遍历每个标签,获取其中的文本内容。最后,将新闻标题打印出来。
原文地址: https://www.cveoy.top/t/topic/oBre 著作权归作者所有。请勿转载和采集!