一个贼有趣的Python爬虫:带你游览微博博主的前世今生!

目录

一、前言 二、项目目标 三、环境配置 四、数据提取分析 4.1 用户微博主页分析 4.2 微博详情页分析 五、代码编写 5.1 创建scrapy项目和爬虫 5.2 修改setting.py 5.3 设置items.py 5.4 编写one_people.py 5.5 编写pipelines.py 5.6 编写midelewares.py 六、结果展示 6.1 评论数据展示 6.2 微博数据展示 七、 项目总结

一、前言

因为疫情的缘故,最近在家老被疫情微博消息轰炸,还每次都忍不住点进去看,关心国内又增长了多少人出院了多少人,国外,尤其是韩国日本伊朗等又激增了多少人,然后看下面大家的评论,看的我胆战心惊的。疫情不分国界,希望大家都能顺顺利利挺过这次全球灾难。

当然,被困在家也要找点事情做,目前在研究爬虫,因为上面提到的微博的事,刚好就把目标放到微博上来了。

接下来我们就一起来爬取微博数据吧!

二、项目目标

  1. 任给一个用户的微博主页链接能够爬取他所有的微博以及点赞数等相关信息。  
  2. 对任意一条微博,可以爬取到他所有的回复,以及回复的点赞数,被回复数。
  3. 将以上两者结合起来,实现对任意一个用户,爬取他的微博信息,所有微博以及每条微博的所有评论信息。
  4. 额外拓展(尚未完成):对每条微博的评论内容再做一次提取,提取评论者id,然后进入评论者主页进行重复爬取,直至完成对整个微博所有用户所有信息的爬取。

三、环境配置

  • 语言:python 3.8.1
  • 开发工具:vscode
  • 浏览器:Chrome
  • 抓包工具:mimtweb
  • 爬虫框架:scrapy 1.8.0

四、数据提取分析

4.1 用户微博主页分析

从电脑进入到微博网站,注意,这里进的是 w.weibo.cn 这个网址,这个是移动端的网址,界面看起来简单很多,少很多干扰因素。

进入到用户微博主页,为了防止你们说我打广告,我进是团团的主页:arrow_down::arrow_down:

用户微博主页

经过chrome的自带工具,我们可以看到这个html页面文件里面什么数据也没有,所以我们判断这个页面的数据是异步加载请求的。我们捕捉这个请求。

扫描二维码关注公众号,回复: 10566715 查看本文章

捕捉异步请求

对请求进行一一分析之后,找到了这个请求微博用户信息的接口,它返回的是标准的json格式数据。里面除了用户信息还有一些其它的数据,我们暂时不知道有什么用,先留着。

接下来我们需要对接口进行优化,这样做是为了提高爬虫效率同时避免因为一些不必要的参数导致请求失败。

我们来看优化前后的请求对比:arrow_down:

优化前的请求

对比优化之后的请求:arrow_down:

优化之后的请求

经过一番折腾,发现对于这个请求而言,url链接里面的containerid是不必要的,可以删去,同时请求头里面很多参数也是不必要的。cookie里面唯一需要保留的就是这个SUB值,如果失去了它,会请求失败。

优化之后我们可以利用用户id来拼凑出请求它主页信息的接口url。

主页url

这是主页的url, u/ 后面那一部分就是用户的id。用这个id拼凑出接口,去掉后面那个containerid值。

拼凑接口

现在微博用户信息的接口找到并优化好之后,就需要开始寻找请求这个微博用户的每一条微博的接口。

请求接口

寻找到了请求微博的接口,但是这部分出现了一个有意思的东西!来观察一下这个新找到的接口。

接口

惊讶的发现,这个接口居然和刚才那个接口惊人的相似!经过分析之后,发现这两个接口之间只有一个地方不同!那就是url后面的 containerid

值。当尝试把这个containerid值删去之后,请求回来的结果果然又变成了之前请求微博用户信息的结果。

然后先将微博往下翻,让他继续请求新的微博信息,得到这样一个url

新微博信息url

与第一次请求微博相比,它又只多了一个参数 since_id ,并且containerid不变,这样的话,我们可以把它理解成起始量,也就是,从哪开始获取新的微博信息。

接下来的任务是寻找到 containerid 和 since_id 的值是从哪获得的。

山重水复疑无路,踏破铁鞋无觅处。柳暗花明又一村,得来全不费功夫。(狗头) containerid值就存放在刚开始请求用户信息的地方。

containerid值

看到这一部分内容,再联想到container这个单词,便可大致理解它为一个容器,所以这个id就是专门存储微博的容器id。

然后联想到since_id的作用,它是用来标明这一次请求微博从哪里开始,那么我们应该能在上一次请求微博返回的信息中找到它,不出我的所料:arrow_down::arrow_down:

since_id位置

然后同样的,优化一下请求微博的接口参数,用户微博主页分析我们就算完成了,来小结一下请求步骤。

  1. 获取用户主页url,获得用户id。
  2. 利用用户id拼凑出请求微博用户信息的接口。
  3. 获取需要的用户信息,并获取微博的containerid值。
  4. 再利用上一个接口和containerid值拼凑出请求微博的第一个接口url。
  5. 获取微博信息之后,利用里面的since_id再拼凑出第二次请求微博的接口url。
  6. 重复第五步直到抓取完毕。

4.2 微博详情页分析

进入一个微博的详情页,简单分析了一下数据来源,发现在详情页里面的微博文本虽然没有直接放在html元素里面呈现出来,但其实并不是异步请求。而是放在了html文件里的js代码内部封装:arrow_down::arrow_down:

详情页内容

我们可以通过正则从html文件中提取出微博的文本数据。

接下来再寻找评论部分的数据来源。

评论的接口网址是这个

评论接口

这个接口中的id和mid数值一样且固定为这条微博的id,而这条微博的id可以从4.1中获取或者是微博详情页URL获取。

这样就可以拼凑出第一批评论接口url。

评论数据来源

这就是第一批评论的数据来源接口了,为什么非要强调这是第一批呢?因为从第二批开始,接口就有所变化了。看一下对比。

第一批

:arrow_down::arrow_down::arrow_down:

第一批之后

从这里看出来,从第二批评论开始,接口中就多了一个参数 max_id

,而经过抓包修改测试,这个参数无法去除,同时数值也需要准确,会不停变化。

那么这个max_id从哪来呢?

还记得4.1 的时候分析的那个数值since_id嘛?从前一个接口里面获取到下一个接口需要的参数。这里也是一样的道理!

来看一下通过获取第一批评论的接口获取到的数据下方:

数据

果不其然这里有我们需要的max_id,这样我们就能很简单的拼凑出再下一批的接口url了。

等一下。你以为这样就算完了?

不!经过我的踩坑,这里还有一个很需要注意的地方,就是那个不起眼的 max_id_type 。

在上面的接口url中,它一直都等于0,但是事实上,它是会变成1的。并且暂时没有摸清具体什么时候变。

这个坑,如果踩过就很简单,因为max_id_type的值也是与max_id一同知道了的,但是如果没踩过,很容易误认为就永远为0。

优化一下请求的接口参数:

优化评论接口

这里的cookie同样只需要SUB,值与4.1相同且不变,如果失去这个SUB会被重定向导致获取不到数据。

小结一下4.2:

  1. 从微博详情页html里面用正则提取出文本内容。
  2. 利用微博id拼凑出第一批评论请求接口。
  3. 从第一批接口中提取数据,同时利用获取的max_Id 和max_id_type拼凑下一个接口。
  4. 获取数据,拼凑下一个接口。
  5. 重复第四步。

五、代码编写

到了手底下见真章的时候了。开始吧。

5.1 创建scrapy项目和爬虫

不用使用-t crawl模板设置规则来爬去,直接创建一个普通的爬虫就可以

1scrapy startproject weibo
2cd weibo
3scrapy genspider one_people

原谅我粗糙的取名水平。

5.2 修改setting.py

  • robots协议
  • 爬取延迟
  • 默认请求头,关闭cookie
  • 打开管道和下载中间件

首先把遵守robot协议设置为False,同时把爬取延时设置三秒以上

1ROBOTSTXT_OBEY = False
2
3# Configure maximum concurrent requests performed by Scrapy (default: 16)
4#CONCURRENT_REQUESTS = 32
5
6# Configure a delay for requests for the same website (default: 0)
7# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
8# See also autothrottle settings and docs
9DOWNLOAD_DELAY = 3

然后设置一下默认的请求头,并且有很重要的一点是: 将cookies设置为禁用状态 。

因为如果不禁用,那么scrapy框架会根据返回的 set-cookie 值自动生成cookie,最后导致网页被重定向。

 1# Disable cookies (enabled by default)
 2COOKIES_ENABLED = False
 3
 4# Disable Telnet Console (enabled by default)
 5#TELNETCONSOLE_ENABLED = False
 6
 7# Override the default request headers:
 8DEFAULT_REQUEST_HEADERS = {
 9    'host':    'm.weibo.cn',
10    'accept':    'application/json, text/plain, */*',
11    'user-agent':    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36',
12    'accept-encoding':    'gzip, deflate, br',
13    'accept-language':    'zh-CN,zh;q=0.9',
14    'cookie':    'SUB=_2A25zUZngDeRhGeBO6FQW9izFyjuIHXVQvSeorDV6PUNbktANLXPVkW1NShqrqT_gNAKqD3jr0wVYJ8UqOFgnZdeJ;'
15}

然后就是把下载中间件和管道开起来。下载中间件用来随机更换请求头,有必要的话也用来更换ip, 管道用来存储数据。

 1DOWNLOADER_MIDDLEWARES = {
 2    'weibo.middlewares.WeiboDownloaderMiddleware': 543,
 3}
 4
 5# Enable or disable extensions
 6# See https://docs.scrapy.org/en/latest/topics/extensions.html
 7# EXTENSIONS = {
 8#    'scrapy.extensions.telnet.TelnetConsole': None,
 9# }
10
11# Configure item pipelines
12# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
13ITEM_PIPELINES = {
14    'weibo.pipelines.WeiboPipeline': 300,
15}

5.3 设置items.py

为三种爬取的数据聚合设置三个item

item的编写是确定我们要爬取的数据内容,然后可以封装在scrapy.Item类里面从爬虫部分输送到管道部分保存。

 1class CommentItem(scrapy.Item):
 2    '''评论item'''
 3    # 评论时间
 4    comment_time = scrapy.Field()
 5    # 评论文本
 6    text = scrapy.Field()
 7    # 评论人id
 8    comment_people_id = scrapy.Field()
 9    # 评论人name
10    comment_people_name = scrapy.Field()
11    # 评论点赞数
12    comment_likes = scrapy.Field()
13    # 评论回复总数
14    total_number = scrapy.Field()
15
16class PeopleItem(scrapy.Item):
17    '''用户item'''
18    # 用户昵称
19    name = scrapy.Field()
20    # 用户id
21    user_id = scrapy.Field()
22    # 关注数
23    follow_count = scrapy.Field()
24    # 粉丝数
25    followers_count = scrapy.Field()
26    # 描述
27    description = scrapy.Field()
28    # 微博数
29    statuses_count = scrapy.Field()
30    # 是否认证
31    verified = scrapy.Field()
32    # 认证缘由
33    verified_reason = scrapy.Field()
34
35
36class StatusesItem(scrapy.Item):
37    '''微博item'''
38    # 最后编辑于
39    edit_at = scrapy.Field()
40    # 文本
41    text = scrapy.Field()
42    # 转发数
43    reposts_count = scrapy.Field()
44    # 评论数
45    comments_count = scrapy.Field()
46    # 点赞数
47    attitudes_count = scrapy.Field()
48    # 微博id
49    statues_id = scrapy.Field()
50    # 详情页URL
51    origin_url = scrapy.Field()

5.4 编写one_people.py

长代码警告

  1import scrapy
  2import json
  3from weibo.items import PeopleItem, StatusesItem, CommentItem
  4import re
  5
  6
  7class OnePeopleSpider(scrapy.Spider):
  8    name = 'one_people'
  9    allowed_domains = ['w.weibo.cn']
 10    start_urls = ['https://m.weibo.cn/u/3664122147']
 11    usr_id = start_urls[0].split('/')[-1]
 12
 13    def start_requests(self):
 14        '''首先请求第一个js文件,包含有关注量,姓名等信息'''
 15        js_url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=' + \
 16            self.usr_id
 17        yield scrapy.Request(url=js_url,
 18                             callback=self.parse_info,
 19                             dont_filter=True)
 20
 21    def parse_info(self, response):
 22        js = json.loads(response.text)
 23        infos = js['data']['userInfo']
 24        name = infos['screen_name']
 25        user_id = infos['id']
 26        follow_count = infos['follow_count']
 27        followers_count = infos['followers_count']
 28        description = infos['description']
 29        # 微博数
 30        statuses_count = infos['statuses_count']
 31        verified = infos['verified']
 32        verified_reason = ''
 33        if verified == True:
 34            verified_reason = infos['verified_reason']
 35        item = PeopleItem(name=name,
 36                          user_id=user_id,
 37                          follow_count=follow_count,
 38                          followers_count=followers_count,
 39                          description=description,
 40                          statuses_count=statuses_count,
 41                          verified=verified,
 42                          verified_reason=verified_reason)
 43        yield item
 44
 45        weibo_containerid = str(
 46            js['data']['tabsInfo']['tabs'][1]['containerid'])
 47        con_url = '&containerid=' + weibo_containerid
 48        next_url = response.url + con_url
 49        print(next_url)
 50        yield scrapy.Request(url=next_url,
 51                             callback=self.parse_wb,
 52                             dont_filter=True)
 53
 54    def parse_wb(self, response):
 55        try:
 56            js = json.loads(response.text)
 57            datas = js['data']['cards']
 58            for data in datas:
 59                # 去掉推荐位和标签位
 60                if len(data) == 4 or 'mblog' not in data:
 61                    continue
 62                edit_at = data['mblog']['created_at']
 63                text = data['mblog']['text']
 64                reposts_count = data['mblog']['reposts_count']
 65                comments_count = data['mblog']['comments_count']
 66                attitudes_count = data['mblog']['attitudes_count']
 67                statues_id = str(data['mblog']['id'])
 68                origin_url = data['scheme'].split('?')[0]
 69
 70                item = StatusesItem(edit_at=edit_at,
 71                                    text=text,
 72                                    reposts_count=reposts_count,
 73                                    comments_count=comments_count,
 74                                    attitudes_count=attitudes_count,
 75                                    statues_id=statues_id,
 76                                    origin_url=origin_url)
 77                yield item
 78            if 'since_id' not in js['data']['cardlistInfo']:
 79                exit(0)
 80            since_id = str(js['data']['cardlistInfo']['since_id'])
 81            next_url = ''
 82            if 'since_id' not in response.url:
 83                next_url = response.url + '&since_id=' + since_id
 84            else:
 85                next_url = re.sub(r'since_id=\d+', 'since_id=%s' %
 86                                  since_id, response.url)
 87        except Exception as ret:
 88            print("=" * 40)
 89            print("这里出错了: %s" % ret)
 90            print("="*40)
 91            print(js)
 92            print("=" * 40)
 93        yield scrapy.Request(url=next_url,
 94                             callback=self.parse_wb,
 95                             dont_filter=True)
 96
 97        self.comments_url = 'https://m.weibo.cn/comments/hotflow?id={0}∣={1}'.format(statues_id, statues_id)
 98        yield scrapy.Request(url=self.comments_url,
 99                             callback=self.parse_comments,
100                             dont_filter=True)
101
102# =========================================================================
103# 下面这部分爬取每条微博的评论,
104    def parse_comments(self, response):
105        js = json.loads(response.text)
106        max_id = '&max_id=' + str(js['data']['max_id'])
107        next_url = response.url + max_id
108        print("=" * 40)
109        print(next_url)
110        yield scrapy.Request(url=response.url + max_id,
111                             callback=self.parse_comments_next,
112                             dont_filter=True)
113
114    def parse_comments_next(self, response):
115        try:
116            js = json.loads(response.text)
117
118            for comment in js['data']['data']:
119                comment_time = comment['created_at']
120                text = comment['text']
121                comment_people_id = comment['user']['id']
122                comment_people_name = comment['user']['screen_name']
123                comment_likes = comment['like_count']
124                total_number = comment['total_number']
125                item = CommentItem(comment_time=comment_time,
126                                text=text,
127                                comment_people_id=comment_people_id,
128                                comment_people_name=comment_people_name,
129                                comment_likes=comment_likes,
130                                total_number=total_number)
131                yield item
132            max_id = "&max_id=" + str(js['data']['max_id'])
133            max_id_type = '&max_id_type=' + str(js['data']['max_id_type'])
134            print("=" * 40)
135            print(max_id)
136            print(max_id_type)
137            print("=" * 40)
138            yield scrapy.Request(url=self.comments_url + max_id + max_id_type,
139                                callback=self.parse_comments_next,
140                                dont_filter=True)
141        except Exception as ret:
142            print("=" * 40)
143            print("此处出错!%s" % ret)
144            print(response.text)
145            print("=" * 40)

这份爬虫代码,已经将爬取用户微博主页和爬取微博详情页结合了起来,能够实现爬取一个微博用户的所有微博和他所有微博的所有评论功能。

具体的实现涉及到了scrapy框架的应用,利用callback不断跳转处理函数来实现处理不同的信息以及拼凑和传递不同的URL。

同时里面有一些看起来无用的调试代码,能让我在运行scrapy爬虫的时候清楚的看到哪里错了,除了什么问题等。

5.5 编写pipelines.py

  • 根据传入进来的item类不同,将信息放入不同的json文件夹里面去
  • 使用了scrapy内置的json导出类
 1from weibo.items import PeopleItem, StatusesItem, CommentItem
 2
 3
 4from scrapy.exporters import JsonLinesItemExporter
 5class WeiboPipeline(object):
 6    def __init__(self):
 7        self.comments_fp = open("comments.json", "wb")
 8        self.people_fp = open('people.json', 'wb')
 9        self.statuses_fp = open('statuses.json', 'wb')
10        self.comments_exporter = JsonLinesItemExporter(self.comments_fp,
11                                              ensure_ascii=False)
12        self.people_exporter = JsonLinesItemExporter(self.people_fp,
13                                              ensure_ascii=False)
14        self.statuses_exporter = JsonLinesItemExporter(self.statuses_fp,
15                                              ensure_ascii=False)
16
17    def process_item(self, item, spider):
18        if isinstance(item, CommentItem):
19            self.comments_exporter.export_item(item)
20        elif isinstance(item, PeopleItem):
21            self.people_exporter.export_item(item)
22        else:
23            self.statuses_exporter.export_item(item)
24
25        return item
26
27    def close_item(self, spider):
28        print("存储成功!")
29        self.comments_fp.close()
30        self.people_fp.close()
31        self.statuses_fp.close()

5.6 编写midelewares.py

  • 实现自动更换请求头
 1class WeiboDownloaderMiddleware(object):
 2    # Not all methods need to be defined. If a method is not defined,
 3    # scrapy acts as if the downloader middleware does not modify the
 4    # passed objects.
 5    user_agents = [
 6            'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
 7            'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
 8            'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;',
 9            'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',
10            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv,2.0.1) Gecko/20100101 Firefox/4.0.1',
11            'Mozilla/5.0 (Windows NT 6.1; rv,2.0.1) Gecko/20100101 Firefox/4.0.1',
12            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'
13        ]
14
15    def process_request(self, request, spider):
16        user_agent = random.choice(self.user_agents)
17        request.headers['User-Agent'] = user_agent

六、结果展示

6.1 评论数据展示

评论数据展示

6.2 微博数据展示

微博数据展示

七、 项目总结

  • 这次微博数据爬取,对我自己也是一个不小的挑战,刚开始并没有使用mitmweb来抓包分析请求,一直在用jupyter和requests来不断更改请求头来确认需要的值和优化请求,经常会碰到请求数据失败和重定向而导致请求不到数据的问题。
  • 同时,微博的这种前一个请求中带有后一个请求需要的参数这种请求方式刚开始也让我很懵逼,摸不着头脑。
  • 与上文提到的一样,就在我以为成功了的时候,那个max_id_type着实坑了我一把,我想当然的以为这个值恒为0,没算到它居然会变。
  • 接下来想去破解js加密的一些内容和登录的内容,然后去尝试抓取手机app的信息。

更多js解密内容教学案例加群:850591259

发布了5 篇原创文章 · 获赞 0 · 访问量 4226

猜你喜欢

转载自blog.csdn.net/weixin_43881394/article/details/105244249