request,yield爬取网页

来源:互联网 发布:av淘宝改版了怎么回事 编辑:程序博客网 时间:2024/06/06 02:09

首先,在教程(二)(http://blog.csdn.net/u012150179/article/details/32911511)中,研究的是爬取单个网页的方法。在教程(三)(http://blog.csdn.net/u012150179/article/details/34441655)中,讨论了Scrapy核心架构。现在在(二)的基础上,并结合在(三)中提到的爬取多网页的原理方法,进而进行自动多网页爬取方法研究。

并且,为了更好的理解Scrapy核心架构以及数据流,在这里仍采用scrapy.spider.Spider作为编写爬虫的基类。


首先创建project:

 

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. scrapy startproject CSDNBlog  

 

一. items.py编写

在这里为清晰说明,只提取文章名称和文章网址。

 

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. -*- coding:utf-8 -*-  
  2.   
  3. from scrapy.item import Item, Field  
  4.   
  5. class CsdnblogItem(Item):  
  6.     """存储提取信息数据结构"""  
  7.   
  8.     article_name Field()  
  9.     article_url Field()  

 

二. pipelines.py编写

 

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import json  
  2. import codecs  
  3.   
  4. class CsdnblogPipeline(object):  
  5.   
  6.     def __init__(self):  
  7.         self.file codecs.open('CSDNBlog_data.json'mode='wb'encoding='utf-8' 
  8.   
  9.     def process_item(selfitem, spider):  
  10.         line json.dumps(dict(item)) '\n'  
  11.         self.file.write(line.decode("unicode_escape"))  
  12.   
  13.         return item  

其中,构造函数中以可写方式创建并打开存储文件。在process_item中实现对item处理,包含将得到的item写入到json形式的输出文件中。

 


三. settings.py编写

对于setting文件,他作为配置文件,主要是至执行对spider的配置。一些容易被改变的配置参数可以放在spider类的编写中,而几乎在爬虫运行过程中不改变的参数在settings.py中进行配置。

 

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. -*- coding:utf-8 -*-  
  2.   
  3. BOT_NAME 'CSDNBlog'  
  4.   
  5. SPIDER_MODULES ['CSDNBlog.spiders' 
  6. NEWSPIDER_MODULE 'CSDNBlog.spiders'  
  7.   
  8. #禁止cookies,防止被ban  
  9. COOKIES_ENABLED False  
  10.   
  11. ITEM_PIPELINES  
  12.     'CSDNBlog.pipelines.CsdnblogPipeline':300  
  13.  
  14.   
  15. Crawl responsibly by identifying yourself (and your website) on the user-agent  
  16. #USER_AGENT 'CSDNBlog (+http://www.yourdomain.com)'  

 

这里将COOKIES_ENABLED参数置为True,使根据cookies判断访问的站点不能发现爬虫轨迹,防止被ban。

ITEM_PIPELINES类型为字典,用于设置启动的pipeline,其中key为定义的pipeline类,value为启动顺序,默认0-1000。


四. 爬虫编写

爬虫编写始终是重头戏。原理是分析网页得到“下一篇”的链接,并返回Request对象。进而继续爬取下一篇文章,直至没有。

上码:

 

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #!/usr/bin/python  
  2. -*- coding:utf-8 -*-  
  3.   
  4. from scrapy.contrib.spiders import  CrawlSpider,Rule  
  5.   
  6. from scrapy.spider import Spider  
  7. from scrapy.http import Request  
  8. from scrapy.selector import Selector  
  9. from CSDNBlog.items import CsdnblogItem  
  10.   
  11.   
  12. class CSDNBlogSpider(Spider):  
  13.     """爬虫CSDNBlogSpider"""  
  14.   
  15.     name "CSDNBlog"  
  16.   
  17.     #减慢爬取速度 为1s  
  18.     download_delay 1  
  19.     allowed_domains ["blog.csdn.net" 
  20.     start_urls  
  21.   
  22.         #第一篇文章地址  
  23.         "http://blog.csdn.net/u012150179/article/details/11749017"  
  24.      
  25.   
  26.     def parse(selfresponse):  
  27.         sel Selector(response)  
  28.   
  29.         #items []  
  30.         #获得文章url和标题  
  31.         item CsdnblogItem()  
  32.   
  33.         article_url str(response.url)  
  34.         article_name sel.xpath('//div[@id="article_details"]/div/h1/span/a/text()').extract()  
  35.   
  36.         item['article_name'[n.encode('utf-8'for in article_name]  
  37.         item['article_url'article_url.encode('utf-8' 
  38.   
  39.         yield item  
  40.   
  41.         #获得下一篇文章的url  
  42.         urls sel.xpath('//li[@class="next_article"]/a/@href').extract()  
  43.         for url in urls:  
  44.             print url  
  45.             url "http://blog.csdn.net" url  
  46.             print url  
  47.             yield Request(url, callback=self.parse)  

 

慢慢分析:

 

(1)download_delay参数设置为1,将下载器下载下一个页面前的等待时间设置为1s,也是防止被ban的策略之一。主要是减轻服务器端负载。

(2)从response中抽取文章链接与文章题目,编码为utf-8。注意yield的使用。

(3)抽取“下一篇”的url,由于抽取后缺少http://blog.csdn.net部分,所以补充。两个print只为调试,无实际意义。重点在于

 

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. yield Request(url, callback=self.parse)  

也就是将新获取的request返回给引擎,实现继续循环。也就实现了“自动下一网页的爬取”。


五. 执行

 

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. scrapy crawl CSDNBlog  

部分存储数据截图:

 

0 0