关于scrapy爬虫框架

一、选择一个网站

假设要从Mininova网站 中提取所有今天添加的文件的url,name,description和size

网址为 http://www.mininova.org/today

二、定义数据

定义要抓取的数据,通过 Scrapy Items 来实现

例子:(BT文件--bit torrent,比特洪流

【Python】

  1. from scrapy.item import Item, Field  
  2.   
  3. class TorrentItem(Item):  
  4.     url = Field()  
  5.     name = Field()  
  6.     description = Field()  
  7.     size = Field() 


三、撰写蜘蛛

1、查看初始网址的源代码

2、查找url的规律(例子:http://www.mininova.org/tor/+数字,可以利用正则表达式 "/tor/\d+" 来提取所有文件的url地址

3、构建一个Xpath去选择我们需要的数据,name, description 和size

 

【HTML 源码】

  1. <h1>Darwin - The Evolution Of An Exhibition</h1>
  2. <h2>Description:</h2>  
  3.   
  4. <div id="description">  
  5. Short documentary made for Plymouth City Museum and Art Gallery regarding the setup of an exhibit about Charles Darwin in conjunction with the 200th anniversary of his birth.  
  6.   
  7. ...  
  8. <div id="specifications">
  9. <p>  
  10. <strong>Category:</strong> 
  11. <a href="/cat/4">Movies</a> > <a href="/sub/35">Documentary</a>
  12. </p>

  13. <p>
  14. <strong>Total size:</strong>
  15. 150.62 megabyte</p>


从上面代码中,可以发现name在<h1>里面

它的Xpath表达式为://h1/text()


description在id="description"的div标签里

它的Xpath表达式为://div[@id='description']


size它在id="specifications"的div标签中的第2个p标签里

它的Xpath表达式为://div[@id='specification']/p[2]/text()[2]


最后,爬虫的代码如下(python)

  1. from scrapy.contrib.spiders import CrawlSpider, Rule  
  2. from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor  
  3. from scrapy.selector import Selector  
  4.   
  5. class MininovaSpider(CrawlSpider):  
  6.   
  7.     name = 'mininova'  
  8.     allowed_domains = ['mininova.org']  
  9.     start_urls = ['http://www.mininova.org/today']  
  10.     rules = [Rule(SgmlLinkExtractor(allow=['/tor/\d+']), 'parse_torrent')]  
  11.   
  12.     def parse_torrent(self, response):  
  13.         sel = Selector(response)  
  14.         torrent = TorrentItem()  
  15.         torrent['url'] = response.url  
  16.         torrent['name'] = sel.xpath("//h1/text()").extract()  
  17.         torrent['description'] = sel.xpath("//div[@id='description']").extract()  
  18.         torrent['size'] = sel.xpath("//div[@id='specification']/p[2]/text()[2]").extract()  
  19.         return torrent  

四、执行爬虫提取数据

将爬取得到的数据,以json格式保存到scraped_data.json文件中

scrapy crawl mininova -o scraped_data.json -t json

这里用feed export来生成json文件


【Scrapy自带了Feed输出,并且支持多种序列化格式(serialization format)及存储方式(storage backends)。】


五、回顾抓取数据


Selectors 返回的是一个列表(lists)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值