用python写网络爬虫-爬取新浪微博评论
来源:互联网 发布:ubuntu 12.04 163源 编辑:程序博客网 时间:2024/05/29 15:48
新浪微博需要登录才能爬取,这里使用m.weibo.cn这个移动端网站即可实现简化操作,用这个访问可以直接得到的微博id。
分析新浪微博的评论获取方式得知,其采用动态加载。所以使用json模块解析json代码
单独编写了字符优化函数,解决微博评论中的嘈杂干扰字符
本函数是用python写网络爬虫的终极目的,所以采用函数化方式编写,方便后期优化和添加各种功能
# -*- coding:gbk -*-import reimport requestsimport jsonfrom lxml import html#测试微博4054483400791767comments=[]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-1def 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 comment3def get_responses(id,page): url="https://m.weibo.cn/api/comments/show?id={}&page={}".format(id,page) response=requests.get(url) return responsedef 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))
阅读全文
1 0
- 用python写网络爬虫-爬取新浪微博评论
- [Python爬虫] Selenium爬取新浪微博移动端热点话题及评论 (下)
- 用python写爬虫爬取腾讯视频的评论
- [Python爬虫] Selenium爬取新浪微博客户端用户信息、热点话题及评论 (上)
- 使用python网络爬虫爬取新浪新闻(一)
- 【python 新浪微博爬虫】python 爬取新浪微博24小时热门话题top500
- 新浪微博评论爬虫小DEMO
- python爬虫——用selenium和phantomjs对新浪微博PC端进行爬取(二)
- [python爬虫] Selenium爬取新浪微博内容及用户信息
- python爬虫——根据指定关键词爬取新浪微博
- [python爬虫] Selenium爬取新浪微博内容及用户信息
- 用Python写一个网络爬虫爬取网页中的图片
- 新浪微博爬虫:模拟登陆+爬取原始页面
- Python新浪微博爬虫
- python新浪微博爬虫
- python爬取新浪微博内容
- 用python写网络爬虫
- 用Python写网络爬虫
- 常见面试题 -- JAVA 小结
- sendfile零拷贝
- 数学&数论 知识总结
- 百度分享插件的使用
- FPN网络
- 用python写网络爬虫-爬取新浪微博评论
- 1 用python进行OpenCV实战之用OpenCV3实现图片载入、显示和储存
- 8.17 H – Frogger
- 常用正则表达式
- java集合之PriorityQueue
- 【Mybatis从0到1-001】开篇
- jsp_2
- 欢迎使用CSDN-markdown编辑器
- Windows单机配置Kafka环境