新浪微指数Scrapy爬虫
写在前面的废话, 最近开始在做爬虫脚本之类的, 然后发现爬虫还是比较简单的(也许吧)。这个脚本写于20180525, 也许将来的某一天他会修改规则。(仅供学习)
关于微博指数的作用,它指的是在指定的时间内一个关键词的热门程度,也许微博热搜热门就是这么来的。还有就是可以对自己感兴趣的关键词进行查询,一次查询时间可以长达两年。
第一步先是进行抓包和测试微指数的工作原理
这就是抓到的json数据包
http://data.weibo.com/index/ajax/getchartdata?month=default&__rnd=1527398996277
我发现他就是一个GET请求,而且参数就两个 模式 和 时间戳,这就非常的困惑啦,那他怎么拿到的数据呢,
第一感觉就是cookie, 所以验证这个假设是不是对的
先使用python requests 这个库进行测试
import requests
import time
cookies = {
"PHPSESSID": "t1st7fkdflo0bungui5mh0fta3",
"WEB3": "1a27ef96cd9c2e4d5d9a43d9ef97e5cc",
# "_s_tentry": "-",
# "Apache": "###,
# "SINAGLOBAL": "###",
# "ULV": "###",
# "UOR": "###",
# "WBStorage": "##"
}
headers = {
'Referer': 'http://data.weibo.com/index',
'User-Agent': '###'
}
data_url = 'http://data.weibo.com/index/ajax/getchartdata?month=default&__rnd=1526970455244'
s = requests.Session()
response = s.get(data_url, headers=headers, cookies=cookies)
print(response.text)
请求到了json数据也当然没有问题,非常好看
经过测试cookie只需要两个参数,而且看不懂他什么意思,也许我搜索的关键词加密
下一步就是怎么弄到这个cookie了
所以从头再来,启用chrome preserve log这个选项, 就不会刷新请求日志了
然后从http://data.weibo.com/index这个页面再来一遍
# http://data.weibo.com/index/ajax/hotword?word=iphonex&flag=nolike&_t=0&__rnd=1527400244197
然后就是一个这样的请求里由我们搜索的关键字iphonex, word是我搜索的关键词, flag&_t是固定的, __rnd是一个时间戳
url = 'http://data.weibo.com/index/ajax/hotword?word=iphonex&flag=nolike&_t=0&__rnd=1527400244197'
html = s.get(url, headers=headers)
print(html.text)
输出的结果如下
response_dict = {"code":"100000","msg":"\u64cd\u4f5c\u6210\u529f","data":{"id":"1030000000269","word":"iphone","is_real":"1"}}
这里面的 id 和 word 和url中的 wid 和 wname 是相对应的
通过这两个参数拼接成搜索的url
http://data.weibo.com/index/hotword?wid=1061709120000146911&wname=iphonex
再次请求这个url 拿到 cookie
req_data = {
'wid': wid,
'wname': wname
}
queries = urlencode(req_data)
url = 'http://data.weibo.com/index/hotword?' + queries
req_res = requests.get(url, headers=headers)
cookies = req_res.cookies.get_dict()
# cookies = {'PHPSESSID': 'erqnu8pe3o17b8ei4o1gq381h5', 'WEB3': 'b2b0f7b82c73f523535a8b5a316def6c'}
至此我们已经拿到了cookie了, 用这个cookie 就能请求出 iphonex 的 json 数据
使用Scrapy进行大量数据的获取
暂时还没有上传到github, 所以直接贴源码
其实只是将上面几个请求集合起来,加上多个关键词,加上时间区间限制
from scrapy import Request, Spider
from urllib.parse import urlencode
import time, requests, json
class WeiboSpider(Spider):
name = 'weibo_index'
def __init__(self):
# 读取 关键词
with open('key_words.txt', encoding='utf-8') as kw_file:
self.word_list = str(kw_file.read()).split('\n') # 获取关键词列表
# sdate=2016-05-23&edate=2018-05-22
self.sdate = '2016-05-23' # 开始时间
self.edate = '2018-05-22' # 结束时间
def start_requests(self):
# 构造请求 获得参数
for word_item in self.word_list:
time_now = str(time.time()).replace('.', '')[:13] # 当前时间
req_data = { # 请求参数
'word': word_item,
'flag': 'nolike',
'_t': '0',
'__rnd': time_now
}
queries = urlencode(req_data)
url = 'http://data.weibo.com/index/ajax/hotword?' + queries
meta = {
'meta_rnd': time_now
}
yield Request(url, callback=self.parse_cookie, meta=meta)
def parse_cookie(self, response):
# 获得cookie 并提交服务器 验证
response_dict = json.loads(response.body_as_unicode())
# response_dict = {"code":"100000","msg":"\u64cd\u4f5c\u6210\u529f","data":{"id":"1061301160000066618","word":"iphone5s","is_real":"1"}}
if response_dict['code'] == "100000":
wid = response_dict['data']['id']
wname = response_dict['data']['word']
# ...
# get cookies ...
# http://data.weibo.com/index/hotword?
# wid=1030000000269&wname=iphone
req_data = {
'wid': wid,
'wname': wname
}
queries = urlencode(req_data)
url = 'http://data.weibo.com/index/hotword?' + queries
# ---- #
headers = {
'Referer': 'http://data.weibo.com/index',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
}
try:
req_res = requests.get(url, headers=headers)
cookies = req_res.cookies.get_dict()
except:
print('>>> 获取 cookies 失败! 请终止并调试 <<<')
# cookies = {'PHPSESSID': 'erqnu8pe3o17b8ei4o1gq381h5', 'WEB3': 'b2b0f7b82c73f523535a8b5a316def6c'}
# ---- #
# ...
# http://data.weibo.com/index/ajax/getchartdata?
# wid=1061301160000066618&sdate=2018-05-01&edate=2018-05-21&__rnd=1526980448823
data_dict = {
'wid': req_data['wid'],
'sdate': self.sdate,
'edate': self.edate,
'__rnd': response.meta['meta_rnd']
}
queries = urlencode(data_dict)
data_url = 'http://data.weibo.com/index/ajax/getchartdata?' + queries
yield Request(data_url, callback=self.parse_index, cookies=cookies, meta=req_data)
else:
print(response_dict)
# print(response.text)
print('错误信息...')
def parse_index(self, response):
response_dict = json.loads(response.body_as_unicode())
# print(response_dict)
# 解析 json dict
yd = response_dict['yd']
for day in yd:
# day = {'daykey': '2018-05-17', 'pc': '895', 'mobile': '15700'}
item = {
'wid': response.meta['wid'],
'wname': response.meta['wname'],
'daykey': day['daykey'],
'mobile': day['mobile'],
'pc': day['pc']
}
# print(item)
yield item
还行吧直接贴上来(滑稽)
这个Scrapy 爬虫脚本的 使用方法
# 说明
## 配置参数
- 修改根目录下的 `key_words.txt`, 一行一个, 编码 `utf-8`
- 修改 `/weibo_index/spider/weibo.py` 中 `__init__` 的时间区间限制
- `pipelines.py` 中设置文件 保存
## 启动方法
- 根目录下运行 shell `scrapy crawl weibo_index`
- `scrapy crawl weibo_index -o items.csv`
写一个保存数据的 Pipeline
编辑 pipeline.py 这个文件,加入如下这个类,将数据储存至CSV,还在项目根目录创建data文件夹
import os
import csv
from scrapy.conf import settings
class FeedCsvPipeline(object):
def process_item(self, item, spider):
filename = os.getcwd() + '\\data\\%s.csv' % (spider.name)
if not os.path.exists(filename):
with open(filename, 'a', newline='', encoding='utf-8') as csvfile:
f = csv.writer(csvfile)
f.writerow(sorted(item.keys()))
with open(filename, 'a', newline='', encoding='utf-8') as csvfile:
f = csv.writer(csvfile)
f.writerow([item[key] for key in sorted(item.keys())])
当然你还需要启用这个pipeline, 编辑 sttings.py 添加启用配置
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
# 'weibo_index.pipelines.WeiboIndexPipeline': 300,
'weibo_index.pipelines.FeedCsvPipeline': 300,
}
当然少部分文件直接-o filename.csv 就可以了,以上代码经过测试并没有受到新浪的限制
写在最后
Scrapy 是一个非常优秀的爬虫框架,可以拓展 scrapy-redis 进行分布式部署
做爬虫的精髓应该在与自己会抓包,理解web 的原理和设计规律,愿世界和平
现在的爬虫越来越难做了, pc端开始受到的限制越来越多,使得爬虫的成本越来越高,最近做了 汽车之家 和 大众点评 的爬虫,真的非常折磨人
真正生产工作中经常需要去抓手机 app 的数据包,这也是解决很多反爬问题的最终方案,当然难度会随着时间的推移越来越大,这也是可以肯定的
如果你幸运的看到了最后,我希望你不断的学习,不管是在学校还是工作中