利用python实现爬取微博评论的方法

发布时间:2021-01-15 17:18:42

来源:亿速云

阅读:79

作者:Leah

本篇文章为大家展示了利用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+[^>]*>')

第三步:设置提取评论functiondef 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

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实现爬取微博评论的方法相关推荐

  1. python抓取微博评论破亿_【python】爬虫-微博评论-武大樱花雨为例 笔记

    〇.前情提要 b站跟着up主 龙王山小青椒 学习爬虫. 参考: python爬虫-微博评论-武大樱花雨为例 https://www.bilibili.com/video/BV1s7411U7AS 人民 ...

  2. python 抓取微博评论破亿_Python爬虫实战演练:爬取微博大V的评论数据

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. 以下文章来源于IT共享之家 ,作者: IT共享者 理论篇 试想一个问题,如果我们要抓取某个微博大V ...

  3. python爬取微博评论破亿_Python爬虫实战演练:爬取微博大V的评论数据

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. 以下文章来源于IT共享之家 ,作者: IT共享者 理论篇 试想一个问题,如果我们要抓取某个微博大V ...

  4. python中data.find_all爬取网站为空列表_利用Golang快速爬取盗版网站的整套音频

    01 前言 最近因为 Zigma 帮我写了个推广 Catcher 小程序软文的原因,答应了他帮他爬了一个盗版音频网站的整套 <李淼谈奇案> . 在制作爬虫脚本的过程中,也是遇到了一些有趣的 ...

  5. python 抓取微博评论破亿_一篇文章教会你使用Python定时抓取微博评论

    [Part1--理论篇] 试想一个问题,如果我们要抓取某个微博大V微博的评论数据,应该怎么实现呢?最简单的做法就是找到微博评论数据接口,然后通过改变参数来获取最新数据并保存.首先从微博api寻找 抓取 ...

  6. python 抓取微博评论破亿_如果利用Python分析14亿条数据!资深程序员手把手教你!过亿级!...

    挑战 1-gram 的数据集在硬盘上可以展开成为 27 Gb 的数据,这在读入 python 时是一个很大的数据量级.Python可以轻易地一次性地处理千兆的数据,但是当数据是损坏的和已加工的,速度就 ...

  7. 下面哪个python库不能用于提取网页信息_利用python的webscraping库采集抓取爱帮网电话号码...

    利用python的webscraping模块抓取爱帮网电话号码,本文采集该页面的标题和2个电话号码, 具体的python代码: # -*- coding: UTF-8 -*- ''' Created ...

  8. python为啥爬取数据会有重复_利用Python来爬取“吃鸡”数据,为什么别人能吃鸡?...

    原标题:利用Python来爬取"吃鸡"数据,为什么别人能吃鸡? 首先,神装镇楼 背景 最近老板爱上了吃鸡(手游:全军出击),经常拉着我们开黑,只能放弃午休的时间,陪老板在沙漠里奔波 ...

  9. python豆瓣电影top250爬虫课程设计_[教程]图文:爬虫爬取豆瓣电影top250

    window环境下 使用python脚本爬取豆瓣 环境安装 python python开发环境 jupyter python web IDE requests python requests模块用于向 ...

  10. 利用python爬取58同城简历数据_利用python爬取58同城简历数据-Go语言中文社区

    利用python爬取58同城简历数据 最近接到一个工作,需要获取58同城上面的简历信息(http://gz.58.com/qzyewu/).最开始想到是用python里面的scrapy框架制作爬虫.但 ...

最新文章

  1. tf.get_variable
  2. MVC 中的 ViewModel
  3. mysql view none,MySQL笔记之视图的使用详解
  4. 《系统集成项目管理工程师》必背100个知识点-29范围说明书的内容
  5. 几种常见数据库连接池的使用比较
  6. 前端几个笔试题及答案(bd)
  7. 【转】.net框架读书笔记---CLR内存管理\垃圾收集(三)
  8. dev c++ 代码补全_学习干货——玩转DEV—C++
  9. 登月源码登顶 GitHub Top1,37000 Star 致敬人类登月 50 周年!
  10. knight tour java,Knight Tour Problem
  11. Bailian2713 肿瘤面积【基础】
  12. 一台电脑上安装5台tomcat 与 项目部署 probe
  13. PTA程序设计类实验辅助教学平台-基础编程题--JAVA--7.3 逆序的三位数
  14. 连续9年惠及10万贫困家庭 金科“情暖万家”春节送温暖再出发
  15. ArcGIS 网络分析[2.3] 最近设施点
  16. uni-app的安装及使用
  17. Maya XGen 毛发制作3 - 创建发块
  18. 普源精电通过注册:拟募资7.5亿 高瓴与招银是股东
  19. K均值算法(继续优化中)
  20. 神经网络(NN)网络构建及模型算法介绍

热门文章

  1. 微信小程序 通过百度API接口实现汉译英翻译
  2. 数据库特点分析| 寻找你心中的数据库漫威英雄
  3. 仙人掌之歌——路转峰回(2)
  4. 3dmax 导出 fbx文件, 模型 到Unity中 贴图丢失
  5. GPyTorch中的超参数
  6. 破解获取微信小程序源代码
  7. 怎么做好论文查重,分享几个重查方法
  8. 互联网公司的技术体系
  9. 用EOF分解16年东海月平均海表面温度
  10. DP83848IVV硬件电路设计