《python3 网络爬虫开发实战》Ajax结果提取微博信息更新

微博的页面发生了变化,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']
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值