访问黑马程序员论坛抓取人工智能板块帖子获取帖子的标题、作者、发布时间以及链接。
抓取人工智能板块帖子的代码如下:
import requests
from bs4 import BeautifulSoup
# 设置请求头部信息
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 定义函数获取帖子信息
def get_posts_info(url):
# 发送请求
response = requests.get(url, headers=headers)
# 解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 获取帖子列表
posts = soup.find_all('div', class_='list-item')
# 遍历帖子列表,获取帖子信息
for post in posts:
# 获取帖子标题
title = post.find('a', class_='title').text.strip()
# 获取帖子作者
author = post.find('a', class_='author').text.strip()
# 获取帖子发布时间
publish_time = post.find('span', class_='time').text.strip()
# 获取帖子链接
link = post.find('a', class_='title')['href']
# 打印帖子信息
print('标题:', title)
print('作者:', author)
print('发布时间:', publish_time)
print('链接:', link)
print('--------------------------')
# 测试函数
if __name__ == '__main__':
url = 'https://bbs.itheima.com/forum-ai-1.html'
get_posts_info(url)
运行代码后,可以获取人工智能板块的帖子信息,包括标题、作者、发布时间和链接。
原文地址: https://www.cveoy.top/t/topic/bqeI 著作权归作者所有。请勿转载和采集!