Python实现新浪微博移动端评论爬取详解
本文详解如何利用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爬取新浪微博评论的完整流程与代码整合。希望本文的内容能对大家有所帮助。若有任何疑问,欢迎留言交流,小编会及时回复。同时,感谢大家对本网站的支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













