scrapy是一个应用框架,用于web网站爬虫;获取有用数据,用于自己的应用
spider 实例
import scrapy class StackOverflowSpider(scrapy.Spider): name = 'stackoverflow' start_urls = ['http://stackoverflow.com/questions?sort=votes'] def parse(self, response): for href in response.css('.question-summary h3 a::attr(href)'): full_url = response.urljoin(href.extract()) yield scrapy.Request(full_url, callback=self.parse_question) def parse_question(self, response): yield { 'title': response.css('h1 a::text').extract_first(), 'votes': response.css('.question .vote-count-post::text').extract_first(), 'body': response.css('.question .post-text').extract_first(), 'tags': response.css('.question .post-tag::text').extract(), 'link': response.url, }将spider 保存到
stackoverflow_spider.py
;
运行spider
scrapy runspider stackoverflow_spider.py -o top-stackoverflow-questions.json
意思是运行stackoverflow_spider.py,将title,votes,body,tags,link保存到top-stackoverflow-questions.json文件中 。
top-stackoverflow-questions.json文件内容
[{ "body": "... LONG HTML HERE ...","link": "http://stackoverflow.com/questions/11227809/''why-is-processing-a-sorted-array-faster-than-an-unsorted-array","tags": ["java", "c++", "performance", "optimization"],"title": "Why is processing a sorted array faster than an unsorted array?","votes": "9924" },
{ "body": "... LONG HTML HERE ...","link": "http://stackoverflow.com/questions/1260748/''how-do-i-remove-a-git-submodule","tags": ["git", "git-submodules"],"title": "How do I remove a Git submodule?","votes": "1764" },...]发生了什么?
当运行命令:scrapy runspider somefile.py ,scrapy 查找spider,然后通过crawl 引擎运行spidercrawl 请求 start_url中的网址,默认回调parse(),将response 作为参数传递给parse方法;在parse方法中,请求response中的URL,并回调 parse_question方法注:yield 类似于return,但是不会像return一样终止程序,而是继续下一个循环这里有一点scrapy的主要优势:请求是异步调度的。这意味着srapy不需要等到请求一个请求完成后再运行后续操作,它可以发送另一个请求,或者在同一 时间做其他的事情。这样能够快速的爬虫。当然,你也可以设置每个请求的间隔时间,限制每个域名或者ip的请求数量最后,parse_question 返回每一页面数据,存储字典形式,写入json文件what's next?
下一步,将介绍scrapy 安装,学习scrapy 项目的组成,感谢大家~