爬取百度贴吧发帖信息并保存到scv文件中
#爬取百度贴吧的发贴信息(https://tieba.baidu.com/f?kw=%E7%88%AC%E8%99%AB&ie=utf-8&pn=50),并通过正则表达式解析数据,包括发帖标题、发帖人、发帖时间,保存到csv文件。
#导入需要的模块
import requests
import re
import csv
url="https://tieba.baidu.com/f?kw=%E7%88%AC%E8%99%AB&ie=utf-8&pn=50"
# 1.获取网页源代码
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Mobile Safari/537.36"
}
response=requests.get(url,headers=headers) #发送请求
html=response.content.decode(encoding='utf-8') #获取网页源代码
#2.解析数据
xinxi_list=[]
title = re.compile('"j_th_tit ">(.*)</a>')
titles = re.findall(title, html) #获取标题
author = re.compile('"主题作者: (.*)"')
authors = re.findall(author, html) #获取发帖人
time = re.compile(r'"创建时间">(.*)</span>')
times = re.findall(time, html) #获取发帖时间
for i in range(len(titles)):
xinxi = {
"标题": titles[i],
"发帖人": authors[i],
"发帖时间": times[i]
}
xinxi_list.append(xinxi)
#保存成csv文件
with open('发帖信息.csv', 'w', encoding='utf-8') as f: # 打开指定文件,如果文件不存在则创建同名的文件
w = csv.DictWriter(f, fieldnames=['标题', '发帖人','发帖时间']) # 指定写入文件的字段名
w.writeheader() # 写入表头
w.writerows(xinxi_list) # 写入列表中的数据
print("爬取完成")