Python实现新浪微博移动端评论爬取详解

七月
七月
发布时间:2026-10-13| 6人浏览过
原创

本文详解如何利用Python爬取新浪微博移动端评论。通过访问m.weibo.cn获取微博ID,分析其动态加载机制,使用requests和json模块获取数据。文中提供了去除干扰字符的优化函数,并对代码进行模块化封装,便于后续功能扩展与优化,旨在为开发者提供一套完整的微博评论抓取方案。

微博移动端数据获取基础

由于新浪微博要求登录状态才能获取完整数据,本文采用移动端站点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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。