爬取目标用户的微博

  • 一、目标页面
  • 二、解析页面内容
  • 三、整个过程
  • 四、结果展示

写在前面:微博有三个网站,不同的网站爬取得难度不同,分别是
网页端: http://weibo.com;
手机端: http://m.weibo.cn;
移动端: http://weibo.cn。

本篇主要爬取微博手机端的目标用户的微博内容,所谓目标用户是指,给定的用户id,而不是通过信息搜索得到。

一、目标页面

首先确定好目标用户,这里选择知名演员李现的微博账号。爬取数据不用于非法或者违规的用途,单纯用于学习研究。
打开李现的微博主页,在链接中可以看到他的账号id是2360812967,这个是用来识别每个微博账号的id。

这是打开网页的源代码,会发现里面没有我们直接看到的如图中的内容,因为页面是通过Ajax动态渲染得到的,所以直接的网页源代码中没有内容。所以需要打开页面的开发者工具页面,找到对应的网页信息。在XHR中可以看到getIndex?这个链接中有对应的微博信息。而且往下滑会出现更多的微博和对应的getIndex?的链接。大概可以确定这个就是要爬取得目标页面。

接下来得问题,就是找到对应得页面得URL,尤其是向下滑得过程中产生得新的页面。
简单对比和分析可以发现,第二个getindex?开始是关于用户发博得内容。
header中得request URL分别是:

  • https://m.weibo.cn/api/container/getIndex?type=uid&value=2360812967&containerid=1076032360812967
  • https://m.weibo.cn/api/container/getIndex?type=uid&value=2360812967&containerid=1076032360812967&since_id=4537401894771336
  • https://m.weibo.cn/api/container/getIndex?type=uid&value=2360812967&containerid=1076032360812967&since_id=4528777969276951
    后面得URL中多了一个since_id 的参数,肉眼上并看不出有什么规律,但是在开发者工具页面中,可以找到这个since_id参数。比如第三个URL中的since_id参数就是从第二个URL中response中得到的since_id。即向下滑的过程中,新产生的页面链接中的since_id参数与当前页面中得到的since_id参数有关。根据这个逻辑,我们就可以构造函数来获得当前页面的这个参数组成下一个访问页面的URL链接。
def get_since_id(count_id,header,sin_id):
#构造一个函数得到当前页面的since_id参数import requests,timefrom urllib.parse import urlencodebase_url='https://m.weibo.cn/api/container/getIndex?'info={'uid':str(count_id),'type':'uid','value':str(count_id),'containerid':'107603'+str(count_id),'since_id':sin_id}URL=base_url+urlencode(info)#构造当前页面的URLprint('为了获取下一个since_id的URL:\n',URL)r=requests.get(URL,headers=header)#print(r.json())if r.json()['ok']==0:#如果正常访问出错time.sleep(3)#休眠时间r=requests.get(URL,headers=header,timeout=6)#应该属于加载错误,重新再加载一次if r.json()['ok']==0:return sin_id#还是出错,则返回当前页面链接中的since_idelif r.json()['ok']==1:#如果正常访问try:since_id=r.json()['data']['cardlistInfo']['since_id']return since_idexcept:r=requests.get(URL,headers=header,timeout=6)try:since_id=r.json()['data']['cardlistInfo']['since_id']return since_idexcept:print(r.json()['data']['cardlistInfo'])#最后一页没有since_id字段 return Noneelif r.json()['ok']==1:try:since_id=r.json()['data']['cardlistInfo']['since_id']#print('下一个since_id:',since_id)return since_idexcept:r=requests.get(URL,headers=header,timeout=6)try:since_id=r.json()['data']['cardlistInfo']['since_id']return since_idexcept:print(r.json()['data']['cardlistInfo'])#最后一页没有since_id字段return None

解决了下一个页面的URL链接问题,接下来就是获得当前页面的有效信息内容。

def get_response(count_id,sin_id):import requestsfrom urllib.parse import urlencodebase_url='https://m.weibo.cn/api/container/getIndex?'info={'uid':str(count_id),'type':'uid','value':str(count_id),'containerid':'107603'+str(count_id),'since_id':sin_id}URL=base_url+urlencode(info)#print(URL)#print('URL:',URL)r=requests.get(URL,headers=headers)response=r.json()['data']['cards']if len(response)<10:#正常来讲,一个页面看了是有10条的微博,如果少于10条,可能是内容加载不全r=requests.get(URL,headers=headers,timeout=6)#再次加载response=r.json()['data']['cards']#获取内容if len(response)==0:#如果没有微博,打印出来方便后续输出print(response)return response

二、解析页面内容

请求得到的内容是json数据结构,层层解析可以知道微博内容相关的信息都在【data】【cards】里面。并且是列表结构

def get_records(items):records=[]error_list=[]key_error_count=0for item in items:#print(item)record={}try:item=item['mblog']except KeyError:key_error_count=key_error_count+1continueelse:try: record['id']=item['id']#微博idrecord['created_at']=item['created_at']#发博时间record['followers_count']=item['user']['followers_count']record['follow_count']=item['user']['follow_count']record['reposts_count']=item['reposts_count']#转发数量comments_num=item['comments_count']record['comments_count']=comments_num#评论数量record['attitudes_count']=item['attitudes_count']#点赞数量record['strategy_display_text_min_number']=item['number_display_strategy']['display_text_min_number']#record['palce_name']=item['product_struct'][0]['name']record['raw_text']=item['raw_text']#微博内容record['pic_num']=item['pic_num']#图片数量if record['pic_num']>0:#如果有图片,并将每个图片的链接保存record['pic_link_num']=len(item['pics'])for i in range(len(item['pics'])):link='pic_link'+str(i+1)record[link]=item['pics'][i]['url']records.append(record)except:error_list.append((item['id'],item['created_at'],item['raw_text']))if len(records)==len(items)-key_error_count:return recordselse:print(error_list)return records

三、整个过程

先将目标账号的信息输入

headers={XXXX}#定义headers
id_=2360812967#目标账号信息
since_id=''#开始为空
all_records=[]#用于存放所有微博记录
n=1
import time
since_id_list=[]
while (n<20):#循环条件设置count=0print('==========================第%d次=============================='%n)response=get_response(id_,since_id)time.sleep(2)print('本次since_id:%s'%since_id)print(len(response))records=get_records(response)print('本次微博条数:',len(records))all_records=all_records+recordssince_id_list.append(since_id)temp_since_id=get_since_id(id_,headers,since_id)while temp_since_id==since_id and count<3:temp_since_id=get_since_id(id_,headers,since_id)count+=1if temp_since_id==since_id and count==3:print ('当前since_id加载失败')breakelif temp_since_id==None:print('未获得下一个since_id')breakelse:since_id=temp_since_idn+=1'''for i in range(len(all_records)):print(all_records[i])'''
print(len(all_records))

四、结果展示



当然可以在解析页面的时候将微博的文本内容进行简单的清洗操作,比如去除换行符等,这样结果就会干净很多。

》》》最后,无论python还是爬虫都刚刚起步,如有问题欢迎指出《《《
》》》》》》》欢迎更多关于爬虫方面的交流《《《《《《《《《《

python3--爬虫--微博爬虫实战相关推荐

  1. python爬虫案例-Python3爬虫三大案例实战分享

    课程名称: [温馨提示:1. 你可以在PC端浏览器或者微信收藏该页面,以方便你快速找到这个课程:2. 课程相关资料可在课程PC端公告查看下载:3.加入课程后,点(课时)列表即可观看视频 ] 课程须知: ...

  2. Python3网络爬虫快速入门实战解析(一小时入门 Python 3 网络爬虫)

    Python3网络爬虫快速入门实战解析(一小时入门 Python 3 网络爬虫) https://blog.csdn.net/u012662731/article/details/78537432 出 ...

  3. python3 爬虫实例_【实战练习】Python3网络爬虫快速入门实战解析(上)

    原标题:[实战练习]Python3网络爬虫快速入门实战解析(上) 摘要 使用python3学习网络爬虫,快速入门静态网站爬取和动态网站爬取 [ 前言 ] 强烈建议:请在电脑的陪同下,阅读本文.本文以实 ...

  4. python微博爬虫实战_32个Python爬虫实战项目,满足你的项目荒,附赠资料

    写在前面 学习Python爬虫的小伙伴想成为爬虫行业的大牛么? 你想在网页上爬取你想要的数据不费吹灰之力么? 那么亲爱的小伙伴们肯定需要项目实战去磨练自己的技术,毕竟没有谁能随随便便成功! 小编前段时 ...

  5. Python3网络爬虫快速入门实战解析

    Python3网络爬虫快速入门实战解析 标签: python网络爬虫 2017-09-28 14:48 6266人阅读 评论(34) 收藏 举报 分类: Python(26) 作者同类文章X 版权声明 ...

  6. Python3 网络爬虫快速入门实战解析

    点击上方"Python高校",关注 文末干货立马到手 作者:Jack Cui http://cuijiahua.com/blog/2017/10/spider_tutorial_1 ...

  7. 实战干货:Python3小说站点爬虫|附下载

    点击上方"Python高校",关注 文末干货立马到手 作者:Jack Cui http://cuijiahua.com/blog/2017/10/spider_tutorial_1 ...

  8. # Python3微博爬虫[requests+pyquery+selenium+mongodb]

    目录 Python3微博爬虫[requests+pyquery+selenium+mongodb] 主要技术 站点分析 程序流程图 编程实现 数据库选择 代理IP测试 模拟登录 获取用户详细信息 获取 ...

  9. Python3 网络爬虫入门与实战

    你将获得 爬虫基本原理 爬虫基本库的使用 爬虫框架/封装设计 必知必会的http原理 讲师介绍 厦门工学院,软件工程 两年爬虫实际开发经验 熟悉Python,Java,C\C++语言开发 Python ...

  10. python爬虫项目实战教学视频_('[Python爬虫]---Python爬虫进阶项目实战视频',)

    爬虫]---Python 爬虫进阶项目实战 1- Python3+Pip环境配置 2- MongoDB环境配置 3- Redis环境配置 4- 4-MySQL的安装 5- 5-Python多版本共存配 ...

最新文章

  1. UA MATH566 统计理论4 贝叶斯统计基础1
  2. Bootstraping, bagging, boosting, AdaBoosting, Rand forest 和 gradient boosting
  3. Java动态代理详解(Proxy+InvocationHandler)
  4. java 生产配置文件管理_JAVA基础——使用配置文件
  5. matlab 增加图像对比度_计算机视觉学习笔记6 图像直方图与直方图均衡化
  6. 如何利用openssl来计算md4, md5, sha1, sha256, sha384, sha512等常用哈希值?
  7. Hive的伴奏_Position Music顶级背景音乐合集243CD
  8. MySQL5.5 RANGE分区增加删除处理
  9. android sdkversion
  10. [转载] python中的内置异常结构
  11. mongodb 集群shard_MongoDB分片集群部署详解
  12. Error response from daemon: Cannot restart container mdet_jc: OCI runtime create failed(fork/exec /)
  13. VB中利用DrawText输出字符串且自动换行
  14. kali之msfconsole
  15. 基于Web的动态新闻发布系统设计与实现(含word文档)
  16. 质数/素数 - 合数
  17. 裸眼3d项目,数字平原是这样制作的
  18. 资金核对平台的发展历程
  19. CNDS 创建属于自己的专栏
  20. 4相5线步进电机驱动原理

热门文章

  1. sql语句查询一条数据的上一条数据和下一条数据
  2. 4284A安捷伦Agilent4284A精密lcr表
  3. Pareto(帕累托)
  4. 华为S7900产品概述
  5. Unity特效学习笔记——刀光
  6. 外卖和快递行业数据_2020年中国即时配送行业市场规模与发展趋势分析 用户和订单量逐年增长【组图】...
  7. 安卓APP合规测试方法“火”了
  8. bluehost虚拟主机速度快吗?bluehost主机评测!
  9. 如何处理 网站被网安大队下发的信息系统安全等级保护限期整改通知书
  10. 爆照(08067CTF) Bugku writeup