python爬取微博评论的实例讲解


Posted in Python onJanuary 15, 2021

python爬虫是程序员们一定会掌握的知识,练习python爬虫时,很多人会选择爬取微博练手。python爬虫微博根据微博存在于不同媒介上,所爬取的难度有差异,无论是python新入手的小白,还是已经熟练掌握的程序员,可以拿来练手。本文介绍python爬取微博评论的代码实例。

一、爬虫微博

与QQ空间爬虫类似,可以爬取新浪微博用户的个人信息、微博信息、粉丝、关注和评论等。

爬虫抓取微博的速度可以达到 1300万/天 以上,具体要视网络情况。

难度程度排序:网页端>手机端>移动端。微博端就是最好爬的微博端。

二、python爬虫爬取微博评论

第一步:确定评论用户的id

# -*- coding:utf-8 -*-
import requests
import re
import time
import pandas as pd
urls = 'https://m.weibo.cn/api/comments/show?id=4073157046629802&page={}'
headers = {'Cookies':'Your cookies',
  'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'}

第二步:找到html标签

tags = re.compile('</?\w+[^>]*>')

第三步:设置提取评论function

def get_comment(url):
j = requests.get(url, headers=headers).json()
comment_data = j['data']['data']
for data in comment_data:
try:

第四步:利用正则表达式去除文本中的html标签

comment = tags.sub('', data['text']) # 去掉html标签
reply = tags.sub('', data['reply_text'])
weibo_id = data['id']
reply_id = data['reply_id']
comments.append(comment)
comments.append(reply)
ids.append(weibo_id)
ids.append(reply_id)

第五步:爬取评论

df = pd.DataFrame({'ID': ids, '评论': comments})
df = df.drop_duplicates()
df.to_csv('观察者网.csv', index=False, encoding='gb18030')

实例扩展:

# -*- coding: utf-8 -*-
# Created : 2018/8/26 18:33
# author :GuoLi
 
import requests
import json
import time
from lxml import etree
import html
import re
from bs4 import BeautifulSoup
 
 
class Weibospider:
 def __init__(self):
  # 获取首页的相关信息:
  self.start_url = 'https://weibo.com/u/5644764907?page=1&is_all=1'
 
  self.headers = {
   "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
   "accept-encoding": "gzip, deflate, br",
   "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
   "cache-control": "max-age=0",
   "cookie": 使用自己本机的cookie,
   "referer": "https://www.weibo.com/u/5644764907?topnav=1&wvr=6&topsug=1",
   "upgrade-insecure-requests": "1",
   "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36",
  }
  self.proxy = {
   'HTTP': 'HTTP://180.125.70.78:9999',
   'HTTP': 'HTTP://117.90.4.230:9999',
   'HTTP': 'HTTP://111.77.196.229:9999',
   'HTTP': 'HTTP://111.177.183.57:9999',
   'HTTP': 'HTTP://123.55.98.146:9999',
  }
 
 def parse_home_url(self, url): # 处理解析首页面的详细信息(不包括两个通过ajax获取到的页面)
  res = requests.get(url, headers=self.headers)
  response = res.content.decode().replace("\\", "")
  # every_url = re.compile('target="_blank" href="(/\d+/\w+\?from=\w+&wvr=6&mod=weibotime)" rel="external nofollow"  ', re.S).findall(response)
  every_id = re.compile('name=(\d+)', re.S).findall(response) # 获取次级页面需要的id
  home_url = []
  for id in every_id:
   base_url = 'https://weibo.com/aj/v6/comment/big?ajwvr=6&id={}&from=singleWeiBo'
   url = base_url.format(id)
   home_url.append(url)
  return home_url
 
 def parse_comment_info(self, url): # 爬取直接发表评论的人的相关信息(name,info,time,info_url)
  res = requests.get(url, headers=self.headers)
  response = res.json()
  count = response['data']['count']
  html = etree.HTML(response['data']['html'])
  name = html.xpath("//div[@class='list_li S_line1 clearfix']/div[@class='WB_face W_fl']/a/img/@alt") # 评论人的姓名
  info = html.xpath("//div[@node-type='replywrap']/div[@class='WB_text']/text()") # 评论信息
  info = "".join(info).replace(" ", "").split("\n")
  info.pop(0)
  comment_time = html.xpath("//div[@class='WB_from S_txt2']/text()") # 评论时间
  name_url = html.xpath("//div[@class='WB_face W_fl']/a/@href") # 评论人的url
  name_url = ["https:" + i for i in name_url]
  comment_info_list = []
  for i in range(len(name)):
   item = {}
   item["name"] = name[i] # 存储评论人的网名
   item["comment_info"] = info[i] # 存储评论的信息
   item["comment_time"] = comment_time[i] # 存储评论时间
   item["comment_url"] = name_url[i] # 存储评论人的相关主页
   comment_info_list.append(item)
  return count, comment_info_list
 
 def write_file(self, path_name, content_list):
  for content in content_list:
   with open(path_name, "a", encoding="UTF-8") as f:
    f.write(json.dumps(content, ensure_ascii=False))
    f.write("\n")
 
 def run(self):
  start_url = 'https://weibo.com/u/5644764907?page={}&is_all=1'
  start_ajax_url1 = 'https://weibo.com/p/aj/v6/mblog/mbloglist?ajwvr=6&domain=100406&is_all=1&page={0}&pagebar=0&pl_name=Pl_Official_MyProfileFeed__20&id=1004065644764907&script_uri=/u/5644764907&pre_page={0}'
  start_ajax_url2 = 'https://weibo.com/p/aj/v6/mblog/mbloglist?ajwvr=6&domain=100406&is_all=1&page={0}&pagebar=1&pl_name=Pl_Official_MyProfileFeed__20&id=1004065644764907&script_uri=/u/5644764907&pre_page={0}'
  for i in range(12): # 微博共有12页
   home_url = self.parse_home_url(start_url.format(i + 1)) # 获取每一页的微博
   ajax_url1 = self.parse_home_url(start_ajax_url1.format(i + 1)) # ajax加载页面的微博
   ajax_url2 = self.parse_home_url(start_ajax_url2.format(i + 1)) # ajax第二页加载页面的微博
   all_url = home_url + ajax_url1 + ajax_url2
   for j in range(len(all_url)):
    print(all_url[j])
    path_name = "第{}条微博相关评论.txt".format(i * 45 + j + 1)
    all_count, comment_info_list = self.parse_comment_info(all_url[j])
    self.write_file(path_name, comment_info_list)
    for num in range(1, 10000):
     if num * 15 < int(all_count) + 15:
      comment_url = all_url[j] + "&page={}".format(num + 1)
      print(comment_url)
      try:
       count, comment_info_list = self.parse_comment_info(comment_url)
       self.write_file(path_name, comment_info_list)
      except Exception as e:
       print("Error:", e)
       time.sleep(60)
       count, comment_info_list = self.parse_comment_info(comment_url)
       self.write_file(path_name, comment_info_list)
      del count
      time.sleep(0.2)
 
    print("第{}微博信息获取完成!".format(i * 45 + j + 1))
 
 
if __name__ == '__main__':
 weibo = Weibospider()
 weibo.run()
 

到此这篇关于python爬取微博评论的实例讲解的文章就介绍到这了,更多相关python爬虫爬取微博评论内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
在Python中封装GObject模块进行图形化程序编程的教程
Apr 14 Python
python使用clear方法清除字典内全部数据实例
Jul 11 Python
详解Python的Django框架中的模版继承
Jul 16 Python
在阿里云服务器上配置CentOS+Nginx+Python+Flask环境
Jun 18 Python
使用Kivy将python程序打包为apk文件
Jul 29 Python
python虚拟环境virtualenv的安装与使用
Sep 21 Python
Python标准库使用OrderedDict类的实例讲解
Feb 14 Python
Python3.5集合及其常见运算实例详解
May 01 Python
PYTHON绘制雷达图代码实例
Oct 15 Python
Python实现简单猜数字游戏
Feb 03 Python
pytorch实现手写数字图片识别
May 20 Python
使用numpy实现矩阵的翻转(flip)与旋转
Jun 03 Python
pycharm 复制代码出现空格的解决方式
Jan 15 #Python
pycharm 实现复制一行的快捷键
Jan 15 #Python
pycharm 快速解决python代码冲突的问题
Jan 15 #Python
使用OpenCV实现人脸图像卡通化的示例代码
Jan 15 #Python
Pycharm 解决自动格式化冲突的设置操作
Jan 15 #Python
pycharm 配置svn的图文教程(手把手教你)
Jan 15 #Python
PyCharm Ctrl+Shift+F 失灵的简单有效解决操作
Jan 15 #Python
You might like
建立动态的WML站点(三)
2006/10/09 PHP
新安装的MySQL数据库需要注意的安全知识
2008/07/30 PHP
支持中文字母数字、自定义字体php验证码代码
2012/02/27 PHP
jQuery总体架构的理解分析
2011/03/07 Javascript
Json2Template.js 基于jquery的插件 绑定JavaScript对象到Html模板中
2011/10/29 Javascript
Prototype源码浅析 String部分(三)之HTML字符串处理
2012/01/15 Javascript
php跨域调用json的例子
2013/11/13 Javascript
利用window.name实现windowStorage代码分享
2014/01/02 Javascript
JavaScript字符串对象replace方法实例(用于字符串替换或正则替换)
2014/10/16 Javascript
js实现两点之间画线的方法
2015/05/12 Javascript
JS字符串的切分用法实例
2016/02/22 Javascript
jQuery封装的屏幕居中提示信息代码
2016/06/08 Javascript
js与applet相互调用的方法
2016/06/22 Javascript
jQuery和JavaScript节点插入元素的方法对比
2016/11/18 Javascript
jQuery实现6位数字密码输入框
2016/12/29 Javascript
JS验证字符串功能
2017/02/22 Javascript
webpack搭建vue 项目的步骤
2017/12/27 Javascript
Vue 样式绑定的实现方法
2019/01/15 Javascript
浅谈 Webpack 如何处理图片(开发、打包、优化)
2019/05/15 Javascript
基于vue的tab-list类目切换商品列表组件的示例代码
2020/02/14 Javascript
基于JS实现计算24点算法代码实例解析
2020/07/23 Javascript
基于javascript原生判断DOM是否加载完毕
2020/10/14 Javascript
如何在vue 中使用柱状图 并自修改配置
2021/01/21 Vue.js
Python正则表达式匹配中文用法示例
2017/01/17 Python
python dict 相同key 合并value的实例
2019/01/21 Python
Python3环境安装Scrapy爬虫框架过程及常见错误
2019/07/12 Python
python2使用bs4爬取腾讯社招过程解析
2019/08/14 Python
导入tensorflow:ImportError: libcublas.so.9.0 报错
2020/01/06 Python
pytorch使用 to 进行类型转换方式
2020/01/08 Python
Python flask路由间传递变量实例详解
2020/06/03 Python
html2canvas生成的图片偏移不完整的解决方法
2020/05/19 HTML / CSS
可口可乐唇膏:Lip Smackers
2019/08/27 全球购物
EJB实例的生命周期
2016/10/28 面试题
酒店员工培训方案
2014/06/02 职场文书
写作之关于描写老人的好段摘抄
2019/11/14 职场文书
Python实战之OpenCV实现猫脸检测
2021/06/26 Python