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

新浪微博需要登录才能爬取,这里使用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代码时,寻找Cookie通常需要以下几个步骤: 1. **登录获取Cookie**: 首先,你需要使用requests库或selenium等工具模拟浏览器访问微博登录页面,通过账号密码登录成功后,浏览器会自动保存一些认证相关的Cookie。你可以查看浏览器开发者工具(如Chrome的DevTools或者Firefox的Web Developer Tools)的Application > Storage (Cookies)部分。 2. **分析请求头**: 当你在浏览器上发送请求时,观察开发者工具里的网络面板,特别是那些成功的登录、授权或者抓取评论的HTTP请求。这些请求的Request Headers里可能包含了Cookie信息。 3. **复制Cookie值**: 在开发者工具中,找到包含"HttpOnly"标志的Cookie,并将其Value部分复制出来。因为通常HttpOnly Cookie不会直接显示在HTML源码中,它们会被浏览器隐藏起来,但对脚本仍然可见。 4. **设置到爬虫代码中**: 将复制的Cookie值添加到Python爬虫的headers或cookies字典中。如果你使用的是requests库,可以这样做: ```python headers = { 'User-Agent': 'Your User Agent', 'Cookie': 'your_cookie_name=your_cookie_value; other_cookies_here' } response = requests.get('https://weibo.com/comments', headers=headers) ``` 5. **处理Session**: 对于更复杂的网站,可能还需要管理session。有些网站会要求将Cookie作为session的一部分存储和传递,这时你可以创建一个requests.Session对象并设置其cookies属性。 请注意,微博可能会有反爬机制,频繁抓取可能触发限制甚至封禁IP,所以请遵守网站的使用款并在实际操作时考虑频率控制和匿名化策略。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值