黑马程序员论坛人工智能板块帖子爬取教程(Python代码)
抓取过程需要使用爬虫技术,以下是Python爬虫代码示例:
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'}
# 发送请求
url = 'https://bbs.itheima.com/forum.php?mod=forumdisplay&fid=60'
response = requests.get(url, headers=headers)
# 解析HTML页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取帖子列表
threads = soup.select('.bm_c .xld')
# 遍历帖子列表,获取帖子信息
for thread in threads:
title = thread.select_one('.xst').text.strip() # 获取帖子标题
author = thread.select_one('.by cite a').text.strip() # 获取帖子作者
time = thread.select_one('.by em span').text.strip() # 获取帖子发布时间
link = thread.select_one('.xst')['href'] # 获取帖子链接
print(title, author, time, link)
运行以上代码,即可获取黑马程序员论坛人工智能板块的帖子标题、作者、发布时间以及链接。
原文地址: https://www.cveoy.top/t/topic/mTsK 著作权归作者所有。请勿转载和采集!