这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!

《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》
《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》
《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》

Scrapy运行流程大概如下:

引擎从调度器中取出一个链接(URL)用于接下来的抓取

引擎把URL封装成一个请求(Request)传给下载器

下载器把资源下载下来,并封装成应答包(Response)

爬虫解析Response

解析出实体(Item),则交给实体管道进行进一步的处理

解析出的是链接(URL),则把URL交给调度器等待抓取

一、安装

因为python3并不能完全支持Scrapy,因此为了完美运行Scrapy,我们使用python2.7来编写和运行Scrapy。

《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》

注:windows平台需要依赖pywin32,请根据自己系统32/64位选择下载安装,https://sourceforge.net/projects/pywin32/

其它可能依赖的安装包:lxml-3.6.4-cp27-cp27m-win_amd64.whl,VCForPython27.msi百度下载即可

《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》

scrapy.cfg 项目的配置信息,主要为Scrapy命令行工具提供一个基础的配置信息。(真正爬虫相关的配置信息在settings.py文件中)

items.py 设置数据存储模板,用于结构化数据,如:Django的Model

pipelines 数据处理行为,如:一般结构化的数据持久化

settings.py 配置文件,如:递归的层数、并发数,延迟下载等

spiders 爬虫目录,如:创建文件,编写爬虫规则

注意:一般创建爬虫文件时,以网站域名命名

《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》

1.爬虫文件需要定义一个类,并继承scrapy.spiders.Spider

2.必须定义name,即爬虫名,如果没有name,会报错。因为源码中是这样定义的:

《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》

3.编写函数parse,这里需要注意的是,该函数名不能改变,因为Scrapy源码中默认callback函数的函数名就是parse;

4.定义需要爬取的url,放在列表中,因为可以爬取多个url,Scrapy源码是一个For循环,从上到下爬取这些url,使用生成器迭代将url发送给下载器下载url的html。源码截图:

《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》
《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》
《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》

4、运行

进入p1目录,运行命令:

《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》

格式:scrapy crawl+爬虫名 –nolog即不显示日志

《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》

示例代码:

def parse ( self , response ) :

# 分析页面

# 找到页面中符合规则的内容(校花图片),保存

# 找到所有的a标签,再访问其他a标签,一层一层的搞下去

hxs = HtmlXPathSelector ( response ) #创建查询对象

# 如果url是 http://www.xiaohuar.com/list-1-\d+.html

if re . match ( ‘http://www.xiaohuar.com/list-1-\d+.html’ , response . url ) : #如果url能够匹配到需要爬取的url,即本站url

items = hxs . select ( ‘//div[@class=”item_list infinite_scroll”]/div’ ) #select中填写查询目标,按scrapy查询语法书写

for i in range ( len ( items ) ) :

src = hxs . select ( ‘//div[@class=”item_list infinite_scroll”]/div[%d]//div[@class=”img”]/a/img/@src’ % i ) . extract ( ) #查询所有img标签的src属性,即获取校花图片地址

name = hxs . select ( ‘//div[@class=”item_list infinite_scroll”]/div[%d]//div[@class=”img”]/span/text()’ % i ) . extract ( ) #获取span的文本内容,即校花姓名

school = hxs . select ( ‘//div[@class=”item_list infinite_scroll”]/div[%d]//div[@class=”img”]/div[@class=”btns”]/a/text()’ % i ) . extract ( ) #校花学校

if src :

ab_src = “http://www.xiaohuar.com” + src [ 0 ] #相对路径拼接

file_name = “%s_%s.jpg” % ( school [ 0 ] . encode ( ‘utf-8’ ) , name [ 0 ] . encode ( ‘utf-8’ ) ) #文件名,因为python27默认编码格式是unicode编码,因此我们需要编码成utf-8

file_path = os . path . join ( “/Users/wupeiqi/PycharmProjects/beauty/pic” , file_name )

urllib . urlretrieve ( ab_src , file_path )

注:urllib.urlretrieve(ab_src, file_path) ,接收文件路径和需要保存的路径,会自动去文件路径下载并保存到我们指定的本地路径。

5.递归爬取网页

上述代码仅仅实现了一个url的爬取,如果该url的爬取的内容中包含了其他url,而我们也想对其进行爬取,那么如何实现递归爬取网页呢?

示例代码:

《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》

即通过yield生成器向每一个url发送request请求,并执行返回函数parse,从而递归获取校花图片和校花姓名学校等信息。

注:可以修改settings.py 中的配置文件,以此来指定“递归”的层数,如: DEPTH_LIMIT = 1

6.scrapy查询语法中的正则:

from scrapy . selector import Selector

from scrapy . http import HtmlResponse

html = “” “

  • first item
  • first item
  • second item
  • ” “”

    response = HtmlResponse ( url = ‘http://example.com’ , body = html , encoding = ‘utf-8’ )

    ret = Selector ( response = response ) . xpath ( ‘//li[re:test(@class, “item-\d*”)]//@href’ ) . extract ( )

    print ( ret )

    语法规则:Selector(response=response查询对象).xpath(‘//li[re:test(@class, “item-d*”)]//@href’).extract(),即根据re正则匹配,test即匹配,属性名是class,匹配的正则表达式是”item-d*”,然后获取该标签的href属性。

    #!/usr/bin/env python

    # -*- coding:utf-8 -*-

    import scrapy

    import hashlib

    from tutorial . items import JinLuoSiItem

    from scrapy . http import Request

    from scrapy . selector import HtmlXPathSelector

    class JinLuoSiSpider ( scrapy . spiders . Spider ) :

    count = 0

    url_set = set ( )

    name = “jluosi”

    domain = ‘http://www.jluosi.com’

    allowed_domains = [ “jluosi.com” ]

    start_urls = [

    “http://www.jluosi.com:80/ec/goodsDetail.action?jls=QjRDNEIzMzAzOEZFNEE3NQ==” ,

    ]

    def parse ( self , response ) :

    md5_obj = hashlib . md5 ( )

    md5_obj . update ( response . url )

    md5_url = md5_obj . hexdigest ( )

    if md5_url in JinLuoSiSpider . url_set :

    pass

    else :

    JinLuoSiSpider . url_set . add ( md5_url )

    hxs = HtmlXPathSelector ( response )

    if response . url . startswith ( ‘http://www.jluosi.com:80/ec/goodsDetail.action’ ) :

    item = JinLuoSiItem ( )

    item [ ‘company’ ] = hxs . select ( ‘//div[@class=”ShopAddress”]/ul/li[1]/text()’ ) . extract ( )

    item [ ‘link’ ] = hxs . select ( ‘//div[@class=”ShopAddress”]/ul/li[2]/text()’ ) . extract ( )

    item [ ‘qq’ ] = hxs . select ( ‘//div[@class=”ShopAddress”]//a/@href’ ) . re ( ‘.*uin=(?P\d*)&’)

    item [ ‘address’ ] = hxs . select ( ‘//div[@class=”ShopAddress”]/ul/li[4]/text()’ ) . extract ( )

    item [ ‘title’ ] = hxs . select ( ‘//h1[@class=”goodsDetail_goodsName”]/text()’ ) . extract ( )

    item [ ‘unit’ ] = hxs . select ( ‘//table[@class=”R_WebDetail_content_tab”]//tr[1]//td[3]/text()’ ) . extract ( )

    product_list = [ ]

    product_tr = hxs . select ( ‘//table[@class=”R_WebDetail_content_tab”]//tr’ )

    for i in range ( 2 , len ( product_tr ) ) :

    temp = {

    ‘standard’ : hxs . select ( ‘//table[@class=”R_WebDetail_content_tab”]//tr[%d]//td[2]/text()’ % i ). extract ( ) [ 0 ] . strip ( ) ,

    ‘price’ : hxs . select ( ‘//table[@class=”R_WebDetail_content_tab”]//tr[%d]//td[3]/text()’ % i ) . extract ( ) [ 0 ] . strip ( ) ,

    }

    product_list . append ( temp )

    item [ ‘product_list’ ] = product_list

    yield item

    current_page_urls = hxs . select ( ‘//a/@href’ ) . extract ( )

    for i in range ( len ( current_page_urls ) ) :

    url = current_page_urls [ i ]

    if url . startswith ( ‘http://www.jluosi.com’ ) :

    url_ab = url

    yield Request ( url_ab , callback = self . parse )

    选择器规则 Demo

    选择器规则 Demo

    选择器规则Demo

    《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》
    《这是我见过最屌的Scrapy框架入门教程!相当于是教科书版的教程!》

    #!/usr/bin/env python

    # -*- coding:utf-8 -*-

    import scrapy

    import hashlib

    from beauty . items import JieYiCaiItem

    from scrapy . http import Request

    from scrapy . selector import HtmlXPathSelector

    from scrapy . spiders import CrawlSpider , Rule

    from scrapy . linkextractors import LinkExtractor

    class JieYiCaiSpider ( scrapy . spiders . Spider ) :

    count = 0

    url_set = set ( )

    name = “jieyicai”

    domain = ‘http://www.jieyicai.com’

    allowed_domains = [ “jieyicai.com” ]

    start_urls = [

    “http://www.jieyicai.com” ,

    ]

    rules = [

    #下面是符合规则的网址,但是不抓取内容,只是提取该页的链接(这里网址是虚构的,实际使用时请替换)

    #Rule(SgmlLinkExtractor(allow=(r’http://test_url/test?page_index=\d+’))),

    #下面是符合规则的网址,提取内容,(这里网址是虚构的,实际使用时请替换)

    #Rule(LinkExtractor(allow=(r’http://www.jieyicai.com/Product/Detail.aspx?pid=\d+’)), callback=”parse”),

    ]

    def parse ( self , response ) :

    md5_obj = hashlib . md5 ( )

    md5_obj . update ( response . url )

    md5_url = md5_obj . hexdigest ( )

    if md5_url in JieYiCaiSpider . url_set :

    pass

    else :

    JieYiCaiSpider . url_set . add ( md5_url )

    hxs = HtmlXPathSelector ( response )

    if response . url . startswith ( ‘http://www.jieyicai.com/Product/Detail.aspx’ ) :

    item = JieYiCaiItem ( )

    item [ ‘company’ ] = hxs . select ( ‘//span[@class=”username g-fs-14″]/text()’ ) . extract ( )

    item [ ‘qq’ ] = hxs . select ( ‘//span[@class=”g-left bor1qq”]/a/@href’ ) . re ( ‘.*uin=(?P\d*)&’ )

    item [ ‘info’ ] = hxs . select ( ‘//div[@class=”padd20 bor1 comard”]/text()’ ) . extract ( )

    item [ ‘more’ ] = hxs . select ( ‘//li[@class=”style4″]/a/@href’ ) . extract ( )

    item [ ‘title’ ] = hxs . select ( ‘//div[@class=”g-left prodetail-text”]/h2/text()’ ) . extract ( )

    yield item

    current_page_urls = hxs . select ( ‘//a/@href’ ) . extract ( )

    for i in range ( len ( current_page_urls ) ) :

    url = current_page_urls [ i ]

    if url . startswith ( ‘/’ ) :

    url_ab = JieYiCaiSpider . domain + url

    yield Request ( url_ab , callback = self . parse )

    spider

    spider

    spider

    上述代码中:对url进行md5加密的目的是避免url过长,也方便保存在缓存或数据库中。

    此处代码的关键在于:

    将获取的数据封装在了Item对象中

    yield Item对象 (一旦parse中执行yield Item对象,则自动将该对象交个pipelines的类来处理)

    # -*- coding: utf-8 -*-

    # Define your item pipelines here

    #

    # Don’t forget to add your pipeline to the ITEM_PIPELINES setting

    # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

    import json

    from twisted . enterprise import adbapi

    import MySQLdb . cursors

    import re

    mobile_re = re . compile ( r ‘(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}’ )

    phone_re = re . compile ( r ‘(\d+-\d+|\d+)’ )

    class JsonPipeline ( object ) :

    def __init__ ( self ) :

    self . file = open ( ‘/Users/wupeiqi/PycharmProjects/beauty/beauty/jieyicai.json’ , ‘wb’ )

    def process_item ( self , item , spider ) :

    line = “%s %s\n” % ( item [ ‘company’ ] [ 0 ] . encode ( ‘utf-8’ ) , item [ ‘title’ ] [ 0 ] . encode ( ‘utf-8’ ) )

    self . file . write ( line )

    return item

    class DBPipeline ( object ) :

    def __init__ ( self ) :

    self . db_pool = adbapi . ConnectionPool ( ‘MySQLdb’ ,

    db = ‘DbCenter’ ,

    user = ‘root’ ,

    passwd = ‘123’ ,

    cursorclass = MySQLdb . cursors . DictCursor ,

    use_unicode = True )

    def process_item ( self , item , spider ) :

    query = self . db_pool . runInteraction ( self . _conditional_insert , item )

    query . addErrback ( self . handle_error )

    return item

    def _conditional_insert ( self , tx , item ) :

    tx . execute ( “select nid from company where company = %s” , ( item [ ‘company’ ] [ 0 ] , ) )

    result = tx . fetchone ( )

    if result :

    pass

    else :

    phone_obj = phone_re . search ( item [ ‘info’ ] [ 0 ] . strip ( ) )

    phone = phone_obj . group ( ) if phone_obj else ‘ ‘

    mobile_obj = mobile_re . search ( item [ ‘info’ ] [ 1 ] . strip ( ) )

    mobile = mobile_obj . group ( ) if mobile_obj else ‘ ‘

    values = (

    item [ ‘company’ ] [ 0 ] ,

    item [ ‘qq’ ] [ 0 ] ,

    phone ,

    mobile ,

    item [ ‘info’ ] [ 2 ] . strip ( ) ,

    item [ ‘more’ ] [ 0 ] )

    tx . execute ( “insert into company(company,qq,phone,mobile,address,more) values(%s,%s,%s,%s,%s,%s)” , values )

    def handle_error ( self , e ) :

    print ‘error’ , e

    pipelines

    pipelines

    上述代码中多个类的目的是,可以同时保存在文件和数据库中,保存的优先级可以在配置文件settings中定义。

    ITEM_PIPELINES = {

    ‘beauty.pipelines.DBPipeline’ : 300 ,

    ‘beauty.pipelines.JsonPipeline’ : 100 ,

    }

    # 每行后面的整型值,确定了他们运行的顺序,item按数字从低到高的顺序,通过pipeline,通常将这些数字定义在0-1000范围内。

    进群:125240963  即可获取十套PDF书籍哦!

        原文作者:学好Python吧
        原文地址: https://www.jianshu.com/p/2cb501de9509
        本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
    点赞