|
发表于 2025-3-7 21:44:22
|
显示全部楼层
让我帮您看看这段代码的问题。您提供的代码存在一些明显的语法错误与逻辑错误。请尝试以下修正:
1. `l =`(行不完整) - 在 GetW 函数中的这个行需要定义 `l`。
2. DitWriter 使用时缺少字段名列表。
3. requests.get 应该使用在 wts 参数,而不是 'wts'。
4. 返回的 JSON 数据中 replies 的结构需要检查,因为对其的处理似乎有误。
改正后的代码如下:
- import requests
- import csv
- import hashlib
- import time
- from urllib.parse import quote
- def GetW(wts, NextPage):
- pagination_str = quote(NextPage)
- l = [
- f"pagination_str={pagination_str}",
- f"wts={wts}"
- ]
- y = '&'.join(l)
- string = y + "ea1db124af3c7062474693fa704f4ff8"
- MD5 = hashlib.md5()
- MD5.update(string.encode('utf-8'))
- w_rid = MD5.hexdigest()
- print(w_rid)
- return w_rid
- def GetContent(offset):
- headers = {
- "cookie": "your_cookie_here",
- "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0"
- }
- url = '[url=https://api.bilibili.com/x/v2/reply/wbi/main']https://api.bilibili.com/x/v2/reply/wbi/main'[/url]
- pagination_str = '{"offset":%s}' % offset
- wts = int(time.time())
- w_rid = GetW(wts=wts, NextPage=pagination_str)
-
- data = {
- 'oid': '114040961501285',
- 'type': '1',
- 'mode': '2',
- 'pagination_str': pagination_str,
- 'plat': '1',
- 'seek_rpid': '',
- 'web_location': '1315875',
- 'w_rid': w_rid,
- 'wts': wts,
- }
-
- response = requests.get(url=url, params=data, headers=headers)
-
- json_data = response.json()
- replies = json_data.get('data', {}).get('replies', [])
- for index in replies:
- dit = {
- '昵称': index.get('member', {}).get('uname', ''),
- '性别': index.get('member', {}).get('sex', ''),
- '地区': index.get('member', {}).get('region', '').replace('IP属地', ''),
- '评论': index.get('content', {}).get('message', ''),
- '点赞': index.get('like', 0),
- }
- print(dit)
- csv_writer.writerow(dit)
- next_offset = json_data.get('data', {}).get('page', {}).get('next', "")
- print(next_offset)
- return next_offset
- if __name__ == '__main__':
- f = open(file='data.csv', mode='w', encoding='utf-8', newline='')
-
- fieldnames = ['昵称', '性别', '地区', '评论', '点赞']
- csv_writer = csv.DictWriter(f, fieldnames=fieldnames)
-
- csv_writer.writeheader()
- offset = ""
-
- for page in range(1, 21):
- offset = GetContent(offset=offset)
- f.close()
复制代码
请确保用您自己的 cookies 替换 "your_cookie_here"。希望这可以帮助您找到并解决问题。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|