前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >抓取个人微博 之 Ajax 数据爬取

抓取个人微博 之 Ajax 数据爬取

作者头像
云雀叫了一整天
发布2019-09-29 17:38:22
4810
发布2019-09-29 17:38:22
举报
文章被收录于专栏:Hi, PythonHi, Python

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/weixin_40313634/article/details/90141841

抓取网站:https://m.weibo.cn/u/2830678474

代码

代码语言:javascript
复制
from urllib.parse import urlencode
import requests
import json
import os
from pyquery import PyQuery as pq

base_url = 'https://m.weibo.cn/api/container/getIndex?'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
    'x-requested-with': 'XMLHttpRequest'
}

# 抓取单个页面
def get_page(page):
    parms = {
        'uid' : '2830678474',
        'luicode' : '10000011',
        'lfid' : '1076032830678474',
        'type' : 'uid',
        'value' : '2830678474',
        'containerid' : '1076032830678474',
        'page' : page
    }
    url = base_url + urlencode(parms)
    try:
        response = requests.get(url, headers = headers)
        if response.status_code == 200:
            return response.json()
    except requests.ConnectionError as e:
        print('Error', e.args)
        return None

# 解析网页内容
def parse_page(json):
    weibo = []
    if json:
        items = json.get('data').get('cards')
        for item in items:
            mblog = item.get('mblog')
            if mblog != None:
                text = pq(mblog.get('text')).text()
                weibo.append(text + '\n\t')
        return weibo

# 获取微博总页数
def sum_page():
    json = get_page(1)
    if json:
        total_item = json.get('data').get('cardlistInfo').get('total')
        sum = int(total_item / 10) + 1
    else:
        sum = 100
    return sum

if __name__ == '__main__':
    sum = sum_page()
    for page in range(sum):
        data = get_page(page)
        weibo = parse_page(data)
        # 保存解析的内容到txt里
        with open('weibo.txt', 'a', encoding = 'utf-8') as f:
            for t in weibo:
                f.write(t)
         # 保存微博每页的数据
        file = os.path.join(os.getcwd(), 'tmp', str(page) + '.json')
        with open(file, 'w', encoding = 'utf-8') as f:
            f.write(json.dumps(data, indent=2, ensure_ascii=False))```
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 抓取网站:https://m.weibo.cn/u/2830678474
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档