如何用python爬虫获取微博评论?
admin
2023-06-26 10:42:21
0次

如何用python爬虫获取微博评论?,相信大部分人都还没学会这个技能,为了让大家学会,给大家总结了以下内容,话不多说,一起往下看吧。

数据格式:{“name”:评论人姓名,“comment_time”:评论时间,“comment_info”:评论内容,“comment_url”:评论人的主页}

以上就是我们需要的信息。

具体操作流程:

我们首相将主页获取完成以后,我们就会发现,其中 的内容带有相关的反爬措施,获取到的源码中的信息含有很多的转义符“\”,并且其中的相关“<”和“>”是通过html的语言直接编写的,这样会导致我们的页面解析出现一定的问题,我们可以用replace方法直接将这些转义符全部去掉,然后我们就可以对这个页面进行正则处理,同时我也尝试过用其他的解析方法,但是其中遇到了很多 的问题,所以我就不过多的介绍了。

当我们获取到了每一篇微博的链接,智汇返佣,还需要获取一个很关键的值 id ,这个值有什么用呢,其主要的作用就是在评论页面的ajax页面的拼接地址上需要使用到。接下来就是需要寻找出我们找到的这两个ajax的url有什么特点或者是规律:

当我们从这些ajax中找到规律以后,不难发现,这个爬虫差不多大功告成了。

下面我就展示一下我的代码:

注意:请在headers中添加自己的cookie

-- 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爬虫获取微博评论的方法介绍,详细使用情况还得要大家自己使用过才能知道具体要领。如果想阅读更多相关内容的文章,欢迎关注行业资讯频道!

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...