💻 源代码
import requests
import json
def get_toutiao_comments(group_id, item_id):
"""获取头条文章评论"""
url = 'https://www.toutiao.com/article/v2/comment/'
params = {
'group_id': group_id,
'item_id': item_id,
'offset': 0,
'count': 20
}
headers = {
'User-Agent': 'Mozilla/5.0 Chrome/91.0.4472.124',
'Referer': 'https://www.toutiao.com/'
}
comments = []
while True:
res = requests.get(url, params=params, headers=headers).json()
data = res.get('data', [])
if not data:
break
for comment in data:
comments.append({
'user': comment['user']['name'],
'content': comment['text'],
'like': comment['digg_count'],
'time': comment['create_time']
})
params['offset'] += 20
if len(data) < 20:
break
return comments
# 使用方法
# 从文章URL获取group_id和item_id
# group_id = 'xxx'
# item_id = 'xxx'
# comments = get_toutiao_comments(group_id, item_id)