详解用python写网络爬虫-爬取新浪微博评论

yipeiwu_com5年前Python爬虫

新浪微博需要登录才能爬取,这里使用m.weibo.cn这个移动端网站即可实现简化操作,用这个访问可以直接得到的微博id。

分析新浪微博的评论获取方式得知,其采用动态加载。所以使用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爬取新浪微博评论详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

python使用beautifulsoup从爱奇艺网抓取视频播放

python使用beautifulsoup从爱奇艺网抓取视频播放

复制代码 代码如下:import sysimport urllibfrom urllib import requestimport osfrom bs4 import Beautiful...

Python爬虫实现(伪)球迷速成

Python爬虫实现(伪)球迷速成

还有4天就世界杯了,作为一个资深(伪)球迷,必须要实时关注世界杯相关新闻,了解各个球队动态,这样才能在一堆球迷中如(大)鱼(吹)得(特)水(吹),迎接大家仰慕的目光! 给大家分享一个快...

python网络爬虫之如何伪装逃过反爬虫程序的方法

有的时候,我们本来写得好好的爬虫代码,之前还运行得Ok, 一下子突然报错了。 报错信息如下: Http 800 Internal internet error 这是因为你的对象网站设置了...

Python爬虫代理IP池实现方法

Python爬虫代理IP池实现方法

在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代理IP,从而保证爬虫快速稳定的运行,当然在公司做的东...

使用Python的Scrapy框架十分钟爬取美女图

使用Python的Scrapy框架十分钟爬取美女图

简介 scrapy 是一个 python 下面功能丰富、使用快捷方便的爬虫框架。用 scrapy 可以快速的开发一个简单的爬虫,官方给出的一个简单例子足以证明其强大: 快速开发 下面开...