Scrapy爬GitHub日记

今天在爬GitHub的时候,发现spider后来很容易就被ban了。后来主要就是要设置header和download_delay;

download_delay = 1

headers = {
    'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
 }

scrapy的输出有时候太多了,挡住了视线。

可以在setting中设置LOG_LEVEL


突然发现,原来GitHub的API有访问限制。

403 reponse
{
"message":"API rate limit exceeded for 58.248.16.36. 
(But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)",
"documentation_url":"https://developer.github.com/v3/#rate-limiting"
}

详情:https://developer.github.com/v3/#rate-limiting

Rate Limiting

For requests using Basic Authentication or OAuth,
you can make up to 5,000 requests per hour.
For unauthenticated requests,
the rate limit allows you to make up to 60 requests per hour.
Unauthenticated requests are associated with your IP address,
and not the user making requests.
Note that the Search API has custom rate limit rules.

认证的可以一个小时5000 requests。非认证的一个小时60 requests,差远了。。。


PyCharm调试Scrapy

scrapy指令其实就是一个python的运行脚本

pyCharm是一个强大的pythonIDE

在运行scrapy库时,其实是相当于运行一个python脚本:

#!/usr/bin/python

from scrapy.cmdline import execute
execute()

所以当运行scrapy crawler spider时,其实与指令:

python /Library/Python/2.7/site-packages/scrapy/cmdline.py crawl spider

的效果是一样的

这样只需要在pycharm中的Run下Edit Configurations…中做运行配置即可:

Name可以随便填

点击ok后,在你的项目中设置断点或者直接运行,即可调试该项目了


如何让scrapy处理403的状态码

1、爬数据的时候,有时会遇到被该网站封IP等情况,response的状态码为403,那么这时候我们希望能够抛出
CloseSpider的异常。
2、但是如scrapy官网提到的,Scrapy默认的设置是过滤掉有问题的HTTP response(即response状态码不在200-300之间)。因此403的情况会被ignore掉,意思就是我们不是处理这个url 请求的response,直接就忽略,也就是及时我们用response.status == 400判断没有作用,因为只有status处于200-300的请求才会被处理。
3. 如果我们想捕获或者处理403,或者其它如404或者500,这种请求时,我们在spider的类中把403放在handle_httpstatus_list中。如下就行。

class MySpider(CrawlSpider):
    handle_httpstatus_list = [403]

或者将403放在HTTPERROR_ALLOWED_CODES设置中
即在settings中增加HTTPERROR_ALLOWED_CODES = [403], HTTPERROR_ALLOWED_CODES默认是[]
http://doc.scrapy.org/en/1.0/topics/spider-middleware.html#httperror-allowed-codes

4. 设置完handle_httpstatus_list或者HTTPERROR_ALLOWED_CODES之后,就可以通过判断response.status == 403抛出CloseSpider异常,结束抓取。


split()函数和GitHub API中的API调用限制

split函数相见恨晚。还有就是GitHub API 的调用限制,是结合了ip和client_id来看的。

不是单单查看client_id和client_secret决定的。


本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。

本站由 @shyiuanchen 创建,使用 Stellar 作为主题。