初识scrapy,美空网图片爬取实战_html/css_WEB-ITnose

WBOY
Freigeben: 2016-06-24 11:53:11
Original
1590 Leute haben es durchsucht

      这俩天研究了下scrapy爬虫框架,遂准备写个爬虫练练手。平时做的较多的事情是浏览图片,对,没错,就是那种艺术照,我骄傲的认为,多看美照一定能提高审美,并且成为一个优雅的程序员。O(∩_∩)O~ 开个玩笑,那么废话不多说,切入正题吧,写一个图片爬虫。

      设计思路:爬取目标为美空网模特照片,利用CrawlSpider提取每张照片的url地址,并将提取的图片url写入一个静态html文本作为存储,打开即可查看图片。 我的环境是win8.1, python2.7+Scrapy 0.24.4,如何配环境我就不说了,大家自行百度一下。

       参照官方文档,我总结了建立爬虫程序大致有四个步骤:

  • 创建一个scrapy project
  • 定义需要从网页中提取的元素item
  • 实现一个spider类,通过接口完成爬取url和提取item的功能
  • 实现一个item pipeline类,完成Item的存储功能。
  •         接下来就很简单了,参照着步骤一步步做就好,首先在终端里面建立一个项目,项目名咱就命名为moko吧。输入指令scrapy startproject moko, scrapy会在当前目录创建一个moko的文件目录,里面有一些初使的文件,文件用处大伙感兴趣查下文档,我主要介绍我们这次用到的文件。

    定义Item  在items.py里面定义我们要抓取的数据:

    # -*- coding: utf-8 -*-# Define here the models for your scraped items## See documentation in:# http://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass MokoItem(scrapy.Item):    # define the fields for your item here like:    # name = scrapy.Field()    url = scrapy.Field()
    Nach dem Login kopieren

  • 这里的url用来存储最后结果的dict号,稍后会继续解释,名字是随意命名的。比如说我还需要爬图片作者的名字,那么我们就可以添加一项name = scrapy.Field(),依次类推。
  • 接下来我们进入spiders文件夹,里面建立一个python文件,名字咱这里就取mokospider.py,添加核心代码实现Spider:
  • Spider是一个继承自scrapy.contrib.spiders.CrawlSpider的Python类,有三个必需的定义的成员

    name: 名字,这个spider的标识,必须是唯一的,不同的爬虫定义不同的名字

    start_urls:一个url列表,spider从这些网页开始抓取

    parse():解析的方法,调用的时候传入从每一个URL传回的Response对象作为唯一参数,负责解析并匹配抓取的数据(解析为item),跟踪更多的URL。

  • # -*- coding: utf-8 -*-#File name :spyders/mokospider.py#Author:Jhonny Zhang#mail:veinyy@163.com#create Time : 2014-11-29#############################################################################from scrapy.contrib.spiders import CrawlSpider,Rulefrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractorfrom moko.items import MokoItemimport refrom scrapy.http import Requestfrom scrapy.selector import Selectorclass MokoSpider(CrawlSpider):    name = "moko"    allowed_domains = ["moko.cc"]    start_urls=["http://www.moko.cc/post/aaronsky/list.html"]    rules = (Rule(SgmlLinkExtractor(allow=('/post/\d*\.html')),  callback = 'parse_img', follow=True),)    def parse_img(self, response):        urlItem = MokoItem()        sel = Selector(response)        for divs in sel.xpath('//div[@class="pic dBd"]'):            img_url=divs.xpath('.//img/@src2').extract()[0]            urlItem['url'] = img_url            yield urlItem
    Nach dem Login kopieren

    咱们的项目命名为moko, 爬虫允许的领域allowed_domains限制在moko.cc,也就是爬虫的约束区域,规定爬虫只爬取这个域名下的网页。爬虫起始地址从 http://www.moko.cc/post/aaronsky/list.html开始。然后设置爬取规则Rule,这是CrawlSpider区别于基础爬虫的地方,打个比方说,咱们从A网页上开始爬,A网页上面有很多超链接url,咱爬虫就根据设定的规则,接着去爬符合规则的超链接url,如此反复下去。callback回调函数,遇到网页调用这个回调函数处理,我之所以没用parse这个默认名字,因为官方文档里说爬虫框架里可能会调用parse,造成冲突。

    目标 http://www.moko.cc/post/aaronsky/list.html网页上有很多图片的链接 ,每个图片的链接都有规律可循,比如说随意点一个打开就是http://www.moko.cc/post/1052776.html,这里的http://www.moko.cc/post/都是一样的,每个链接不同的部分也就是后面数字部分。于是这里我们利用正则表达式,填写规则rules = (Rule(SgmlLinkExtractor(allow=('/post/\d*\.html')), callback = 'parse_img', follow=True),) 指当前网页,所有符合/post/\d*\.html后缀的网页都进行爬取,调用parse_img处理。

    接下来定义解析函数parse_img,这地方比较关键,他传入的参数是爬虫打开url后返回的response对象,response对象里面内容说白了就是很大一些字符串,咱们就是利用爬虫将我们需要的内容过滤出来。如何过滤呢???哈哈,有个牛逼的Selector方法,利用他的xpath()路径表达公式来解析内容,解析前需要具体分析下web页面,我们这里利用的工具就是firebug。截取的web核心代码就是

      我们需要的是src2部分!他在

    标签下的初识scrapy,美空网图片爬取实战_html/css_WEB-ITnose里面, 首先实例一个在Items.py里面定义的MokoItem()的对象urlItem,用牛逼的Selector传入response,我这里用了一个循环,每次处理一个url,利用xpath路径表达式解析取出url,至于xpath如何用,自行百度下。结果存储到urlItem里面,这里用到了我们Items.py里面定义的url了!

    然后定义一下pipelines,这部分管我们的内容存储。

    from moko.items import MokoItemclass MokoPipeline(object):    def __init__(self):        self.mfile = open('test.html', 'w')    def process_item(self, item, spider):        text = '<img src="' + item['url'] + '" alt = "" />'        self.mfile.writelines(text)    def close_spider(self, spider):        self.mfile.close()
    Nach dem Login kopieren

    建立一个test.html文件用来存储结果。注意我的process_item里用到了一些html规则,作用是直接在html里面显示图片。结尾在定义一个关闭文件的方法,在爬虫结束时候调用。

    最后定义设置一下settings.py

    BOT_NAME = 'moko'SPIDER_MODULES = ['moko.spiders']NEWSPIDER_MODULE = 'moko.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent#USER_AGENT = 'moko (+http://www.yourdomain.com)'ITEM_PIPELINES={'moko.pipelines.MokoPipeline': 1,}     
    Nach dem Login kopieren

     


     

          最后展示一下效果图吧,祝各位玩的快乐 ^_^

                   

    Quelle:php.cn
    Erklärung dieser Website
    Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
    Beliebte Tutorials
    Mehr>
    Neueste Downloads
    Mehr>
    Web-Effekte
    Quellcode der Website
    Website-Materialien
    Frontend-Vorlage
    Über uns Haftungsausschluss Sitemap
    Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!