用python写网络爬虫-爬取新浪微博评论
2017-08-17 16:04
561 查看
新浪微博需要登录才能爬取,这里使用m.weibo.cn这个移动端网站即可实现简化操作,用这个访问可以直接得到的微博id。
分析新浪微博的评论获取方式得知,其采用动态加载。所以使用json模块解析json代码
单独编写了字符优化函数,解决微博评论中的嘈杂干扰字符
本函数是用python写网络爬虫的终极目的,所以采用函数化方式编写,方便后期优化和添加各种功能
分析新浪微博的评论获取方式得知,其采用动态加载。所以使用json模块解析json代码
单独编写了字符优化函数,解决微博评论中的嘈杂干扰字符
本函数是用python写网络爬虫的终极目的,所以采用函数化方式编写,方便后期优化和添加各种功能
# -*- coding:gbk -*- import re import requests import json from lxml import html #测试微博4054483400791767 comments=[] def get_page(weibo_id): url='https://m.weibo.cn/status/{}'.format(weibo_id) html=requests.get(url).text regcount=r'"comments_count": (.*?),' comments_count=re.findall(regcount,html)[-1] comments_count_number=int(comments_count) page=int(comments_count_number/10) return page-1 def opt_comment(comment): tree=html.fromstring(comment) strcom=tree.xpath('string(.)') reg1=r'回复@.*?:' reg2=r'回覆@.*?:' reg3=r'//@.*' newstr='' comment1=re.subn(reg1,newstr,strcom)[0] comment2=re.subn(reg2,newstr,comment1)[0] comment3=re.subn(reg3,newstr,comment2)[0] return comment3 def get_responses(id,page): url="https://m.weibo.cn/api/comments/show?id={}&page={}".format(id,page) response=requests.get(url) return response def get_weibo_comments(response): json_response=json.loads(response.text) for i in range(0,len(json_response['data'])): comment=opt_comment(json_response['data'][i]['text']) comments.append(comment) weibo_id=input("输入微博id,自动返回前5页评论:") weibo_id=int(weibo_id) print('\n') page=get_page(weibo_id) for page in range(1,page+1): response=get_responses(weibo_id,page) get_weibo_comments(response) for com in comments: print(com) print(len(comments))
相关文章推荐
- [Python爬虫] Selenium爬取新浪微博移动端热点话题及评论 (下)
- 用Python制作新浪微博爬虫
- Python编写网络爬虫--牛刀小试
- [python]简单的网络爬虫
- 读书笔记--用Python写网络爬虫00--建立练习环境
- 网络爬虫:从python2到python3
- (一)表层网络信息获取(Python引擎爬虫)
- Python 网络爬虫 007 (编程) 通过网站地图爬取目标站点的所有网页
- python实现网络爬虫
- python网络应用入门:网络爬虫的使用
- python:网络爬虫入门经验总结大大大大全
- [No000079]罗辑思维2016.1.2日前的所有每日语音,python3做的网络爬虫
- [Python]网络爬虫(九):百度贴吧的网络爬虫(v0.4)源码及解析
- [Python]网络爬虫(九):百度贴吧的网络爬虫(v0.4)源码及解析
- 【python学习】网络爬虫——基础案例教程
- python网络爬虫之使用scrapy爬取图片
- Python网络爬虫基础知识学习
- python爬虫selenium+firefox抓取京东商品评论
- Python网络爬虫——1、初识网络爬虫
- Python爬虫实例_城市公交网络站点数据的爬取方法