微博的页面发生了变化,page变量换成了since_id,作者已经在github上更新了源码https://github.com/Python3WebSpider/WeiboList/issues/9。
此外,这里还有一个博主找到了since_id的变化规律https://blog.csdn.net/weixin_44489501/article/details/104119556
github上的代码好像只能爬取11页,我写的应该可以爬取全部的微博:
from urllib.parse import urlencode
import requests
from pyquery import PyQuery as pq
base_url = 'https://m.weibo.cn/api/container/getIndex?'
headers = {
'Host': 'm.weibo.cn',
'Referer': 'https://m.weibo.cn/u/2830678474',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
}
def get_since_id(since_id):
params = {
'type': 'uid',
'value': '2830678474',
'containerid': '1076032830678474',
'since_id': since_id
}
url = base_url + urlencode(params)
print(url)
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
except requests.ConnectionError as e:
print('Error', e.args)
def parse_since_id(json):
if json:
since_id = json.get('data').get('cardlistInfo').get('since_id')
items = json.get('data').get('cards')
for item in items:
item = item.get('mblog')
weibo = {}
weibo['id'] = item.get('id')
weibo['text'] = pq(item.get('text')).text()
weibo['attitudes'] = item.get('attitudes_count')
weibo['comments'] = item.get('comments_count')
weibo['reposts'] = item.get('reposts_count')
weibo['since_id'] = since_id
yield weibo
if __name__ == '__main__':
json = get_since_id("")
results = parse_since_id(json)
for result in results:
print(result)
since_id = result['since_id']
while since_id:
json = get_since_id(since_id)
results = parse_since_id(json)
for result in results:
print(result)
since_id = result['since_id']