首页 > 代码库 > Scrapy爬虫 -- 02
Scrapy爬虫 -- 02
爬虫最基本的部分是要将网页下载,而最重要的部分是过滤 -- 获取我们需要的信息。
而scrapy正好提供了这个功能:
首先我们要定义items:
Itemsare containers that will be loaded with the scraped data; they work like simple python dicts but provide additional protection against populating undeclared fields, to prevent typos.
摘自官网,大意就是说iteams是用来存储抓取的数据结构,提供相对与python字典类型额外的类型保护。(这个具体的保护方式待研究)
示例如下:
project/items.py
import scrapyclass DmozItem(scrapy.Item): title = scrapy.Field() link = scrapy.Field() desc = scrapy.Field()
然后我们需要编写Spider,抓取网页并选择信息,将其放入items之中。
示例如下:
import scrapyclass DmozSpider(scrapy.Spider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ] def parse(self, response): filename = response.url.split("/")[-2] with open(filename, ‘wb‘) as f: f.write(response.body)
说明:
name Spider的名字,这个名字要在这个项目之中唯一,原因稍后就知道了。
allowed_domains,这个是域名设置,即是否抓取其他域名,一般摄制成要start_urls中地址的域名即可
- start_urls 这是一个列表,表示scrapy抓取网页的起始位置,以样例为例,如果你要抓取http://www.dmoz.org/Computers/Programming/Languages/Python/Books/中所有的图书,那start_urls就是上述网址。
- parse函数 个人认为类似于java中接口的概念,scrapy向网站发出request,然后调用DmozSpider中的parse函数对返回的response进行处理。
开始启动蜘蛛:
scrapy crawl dmoz
正常的化输出如下:
2014-01-23 18:13:07-0400 [scrapy] INFO: Scrapy started (bot: tutorial) 2014-01-23 18:13:07-0400 [scrapy] INFO: Optional features available: ... 2014-01-23 18:13:07-0400 [scrapy] INFO: Overridden settings: {} 2014-01-23 18:13:07-0400 [scrapy] INFO: Enabled extensions: ... 2014-01-23 18:13:07-0400 [scrapy] INFO: Enabled downloader middlewares: ... 2014-01-23 18:13:07-0400 [scrapy] INFO: Enabled spider middlewares: ... 2014-01-23 18:13:07-0400 [scrapy] INFO: Enabled item pipelines: ... 2014-01-23 18:13:07-0400 [dmoz] INFO: Spider opened 2014-01-23 18:13:08-0400 [dmoz] DEBUG: Crawled (200) <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/> (referer: None) 2014-01-23 18:13:09-0400 [dmoz] DEBUG: Crawled (200) <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/> (referer: None) 2014-01-23 18:13:09-0400 [dmoz] INFO: Closing spider (finished)
待续
Scrapy爬虫 -- 02
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。