详解用python写网络爬虫-爬取新浪微博评论

(编辑:jimmy 日期: 2024/9/28 浏览:2)

新浪微博需要登录才能爬取,这里使用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": (.*"https://m.weibo.cn/api/comments/show".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爬取新浪微博评论详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。