开发环境:
实现流程:
一. 思路分析
找到数据来源
network 记录网页数据 请求
二. 实现代码
- 发送请求
- 获取数据
- 解析数据
- 保存数据
代码展示
导入模块
import requests # 需要额外安装
import csv
半成品 (最基本的架构)
f = open('评论.csv', mode='a', encoding='utf-8-sig', newline='')
csv_writer = csv.writer(f)
csv_writer.writerow(['id', 'text_raw', 'source', 'like_counts', 'screen_name', 'followers_count'])
请求头
headers = {
# 用户身份信息
'cookie': 'SINAGLOBAL=2983116536906.6313.1675064186827; UOR=,,www.baidu.com; SUB=_2A25O3LQhDeRhGeNH6lIY-CjFyT-IHXVqPtxprDV8PUJbkNANLXXDkW1NSsgssEqW-GyChLyvK7V0MBeFYsy23ElC; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WWNoXNAv0FwwfrPTiDyBL285NHD95Qf1K271Knc1Kz0Ws4Dqcjci--4iK.Ri-zXi--fi-2Xi-24i--Xi-zRiKy2i--4iKnfiKy2i--fi-isi-8Fi--Xi-z4iK.7; XSRF-TOKEN=gSKn52W-3CqnU16SUOqIOY5r; _s_tentry=weibo.com; Apache=3694052218654.842.1675252819884; ULV=1675252819940:5:2:5:3694052218654.842.1675252819884:1675237842632; WBPSESS=Q4mocWB9j3toNvru27wa1agqFWvDlaxybkjDQlV26btT8dAjnZKLHT6p8NAwVhAzIbygYan56xOn7f0H4XAe_IymVa9GmASzrKUCqV6J_Ml2bYGTL_URVrA5YnjNm62kuNboZbV4Cpn1MZTfoLbEWg==',
# 防盗链
'referer': 'https://***.com/1223178222/MqQsvemFc',
# 浏览器基本信息
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
}
next = 'count=10'
1. 发送请求
while True:
url = f'https://****.com/ajax/statuses/buildComments?is_reload=1&id=4863981833423714&is_show_bulletin=2&is_mix=0&{next}&uid=1223178222'
response = requests.get(url=url, headers=headers)
2. 获取数据
.text: 获取文本数据
.json(): json字符串数据
.content: 获取二进制数据
2.1 出现乱码
json_data = response.json()
3. 解析数据
结构化数据 : json数据{}包裹的格式 转成字典, 使用字典取值 re
非结构化数据: 网页源代码 lxml, bs4, parsel, re css/xpath/re
data_list = json_data['data']
max_id = json_data['max_id']
for data in data_list:
text_raw = data['text_raw']
try:
source = data['source']
except:
source = "未知"
id = data['id']
like_counts = data['like_counts']
screen_name = data['user']['screen_name']
followers_count = data['user']['followers_count']
print(id, text_raw, source, like_counts, screen_name, followers_count)
- 保存数据
csv_writer.writerow([id, text_raw, source, like_counts, screen_name, followers_count])
next = 'max_id='+str(max_id)
尾语
感谢你观看我的文章呐~本次航班到这里就结束啦
希望本篇文章有对你带来帮助 ,有学习到一点知识~
躲起来的星星 也在努力发光,你也要努力加油(让我们一起努力叭)。