python爬取微博评论的实例讲解
作者:宋宋大人 发布时间:2022-01-10 19:53:14
标签:python爬虫,微博评论
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()
来源:https://www.py.cn/spider/example/22977.html


猜你喜欢
- 本文向大家分享了几段Python生成数字图片的代码,喜欢的朋友可以参考。具体如下:最终版本# -*- coding:utf-8 -*-fro
- 一、设置环境在 Ubuntu 机器上安装 SQL Server 2017和安装运行 GoLang 所需的依赖项。1.1、安装 SQL Ser
- 前言神经网络在设置的神经网络足够复杂的情况下,可以无限逼近一段非线性连续函数,但是如果神经网络设置的足够复杂,将会导致过拟合(overfit
- 在 TypeScript 中一共有 7 种基本类型。1、booleanvar isDone: boolean = false;2、numbe
- 形参与实参以及位置参数 什么是形参和实参形参:即形式参数,函数定义时指定的可以接受的参数即为形参,比如定义函数时的max(a,b)函数中的a
- 小编把之前整理的关于mysql 5.7.9 免安装版配置方法分享给大家,供大家参考,具体内容如下1. 解压MySQL压缩包将下载的MySQL
- 下载了一个小型的记帐软件,发现这个软件数据库用的是access,很想看看它的数据库结构怎样,结果人家加密了。access的解密小case了,
- 深入理解 Python 虚拟机:集合(set)的实现原理及源码剖析在本篇文章当中主要给大家介绍在 cpython 虚拟机当中的集合 set
- 使用threading写的一个定时器任务demo:import timeimport sysimport signalimport date
- 一. Python 的类和实例在面向对象中,最重要的概念就是类(class)和实例(instance),类是抽象的模板,而实例是根据类创建出
- Oracle 数据库启动Oracle shutdown的时候突然断电,导致使用sql/plus启动时无法连接到数据库,具体描述为: conn
- 1. OS标准库简介顾名思义,OS表示Operating System,即操作系统。OS标准库是一个操作系统接口模块,提供一些方便使用操作系
- 我们昨天已经学习了python的文件读写,今天来做一个最简单的例子,写一个最简单的缓存系统,要求:以key``value的方式保持数据,并且
- 前言最近又多了不少朋友关注,先在这里谢谢大家。关注我的朋友大多数都是大学生,而且我简单看了一下,低年级的大学生居多,大多数都是为了完成课程设
- 1.元组的创建元组(tuple):元组本身是不可变数据类型,没有增删改查元组内可以存储任意数据类型t = (1,2.3,True,'
- 一、下载地址Apache 5.4 —— httpd-2.4.4-win32.zipPHP 5.4 —— php-5.4.15-Win32-V
- 为了建设班级主页,买了个空间,支持SA FileUp组件。鼓弄了一天,终于有了大致的了解,下面是我的实例,希望对大家有所帮助。大家可以根据自
- python语句与语法1.python简单语句的基本介绍>>> while True: #简单的while循环... re
- 本文实例讲述了js实现黑色简易的滑动门网页tab选项卡效果。分享给大家供大家参考。具体如下:这是一款js实现的黑色风格网页滑动门菜单,虽然简
- 3. 品味“决定”艺术作品的好坏,设计的好坏则来自主观意见我们在鉴赏艺术作品时,用看法来表达当时的感觉,而你的品味则会左右你的看法。以一个有