zoukankan      html  css  js  c++  java
  • scrapy

    ---恢复内容开始---

    Scrapy爬虫介绍

    Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架。 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中。
    其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的, 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。Scrapy用途广泛,可以用于数据挖掘、监测和自动化测试。

    Scrapy功能

    ----引用twisted模块异步下载页面

    -----HTML解析成对象

    -----代理

    ----延迟下载

    ----URL字段去重

    ----指定深度、广度

    ...........................

    Scrapy架构及工作流程

    Scrapy 使用了 Twisted异步网络库来处理网络通讯。整体架构大致如下

     

    Scrapy主要包括了以下组件:

    引擎(Scrapy)
    用来处理整个系统的数据流处理, 触发事务(框架核心)

    调度器(Scheduler)
    用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 可以想像成一个URL(抓取网页的网址或者说是链接)的优先队列, 由它来决定下一个要抓取的网址是什么, 同时去除重复的网址

    下载器(Downloader)
    用于下载网页内容, 并将网页内容返回给蜘蛛(Scrapy下载器是建立在twisted这个高效的异步模型上的)

    爬虫(Spiders)
    爬虫是主要干活的, 用于从特定的网页中提取自己需要的信息, 即所谓的实体(Item)。用户也可以从中提取出链接,让Scrapy继续抓取下一个页面

    项目管道(Pipeline)
    负责处理爬虫从网页中抽取的实体,主要的功能是持久化实体、验证实体的有效性、清除不需要的信息。当页面被爬虫解析后,将被发送到项目管道,并经过几个特定的次序处理数据。

    下载器中间件(Downloader Middlewares)
    位于Scrapy引擎和下载器之间的框架,主要是处理Scrapy引擎与下载器之间的请求及响应。

    爬虫中间件(Spider Middlewares)
    介于Scrapy引擎和爬虫之间的框架,主要工作是处理蜘蛛的响应输入和请求输出。

    调度中间件(Scheduler Middewares)
    介于Scrapy引擎和调度之间的中间件,从Scrapy引擎发送到调度的请求和响应。

    Scrapy运行流程大概如下:

    1.程序员在Spiders里定义爬虫的起始URL。

    2.ScrapyEngine把Spider中的起始URL,推送到Scheduler。

    3.Scheduler调度URL通过Downloader去互联网下载HTML内容。

    4.Downloader下载HTML内容并返回给Spiders(回调函数)。

    5.Spiders调用 Item Pipeline把爬到的内容保存的数据库/文件,或者继续循环流程1-5。

    Scrapy安装&使用

    安装 

    1.Linux

    pip install scrapy

    2.Windows

    2.1:下载twisted 

    Twisted‑18.7.0‑cp36‑cp36m‑win_amd64.whl:cp36是cpython解释器的版本,amd64Windows的位数;

    2.2:安装scrapy

    pip install scrapy -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

    基本使用

    复制代码
    scrapy startproject projectname            #创建1个Scrapy项目
    cd projectname


    scrapy genspider [-t template] <name> <domain> #创建爬虫应用
    scrapy gensipider -t basic le le.com        #创建虫子1
    scrapy gensipider -t xmlfeed bestseller.com.cn  #创建虫子2



    scrapy list                         #展示爬虫应用列表



    scrapy crawl  爬虫应用名 --nolog                  #运行单独爬虫应用 --nolog不打印日志

    修改setings.py
    ROBOTSTXT_OBEY = False:是否遵守爬虫协议
    建议读者一定要遵循爬虫协议,如果ROBOTSTXT_OBEY = True,不能获取到respose一点要和对方打电话谈谈!
     
    复制代码
    # -*- coding: utf-8 -*-
    import scrapy
    
    # import sys,os,io
    # sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') #解决编码错误
    
    class BaiduSpider(scrapy.Spider):
        name = 'baidu'
        allowed_domains = ['baidu.com']      #起始URL
        start_urls = ['http://baidu.com/']  #限制域名
    
        def parse(self, response):             #回调函数
            print(response.text)
    复制代码

    选择器

    复制代码
    # -*- coding: utf-8 -*-
    import scrapy
    from scrapy.selector import Selector, HtmlXPathSelector
    from scrapy.http import HtmlResponse
    # import sys,os,io
    # sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') #解决编码错误
    
    class BaiduSpider(scrapy.Spider):
        name = 'baidu'
        allowed_domains = ['baidu.com']      #起始URL
        start_urls = ['http://baidu.com/']  #限制域名
    
        def parse(self, response):             #回调函数
            html = """<!DOCTYPE html>
            <html>
                <head lang="en">
                    <meta charset="UTF-8">
                    <title></title>
                </head>
                <body>
                    <ul>
                        <li class="item-"><a id='i1' href="link.html">first item</a></li>
                        <li class="item-0"><a id='i2' href="llink.html">first item</a></li>
                        <li class="item-1"><a href="llink2.html">second item<span>vv</span></a></li>
                    </ul>
                    <div><a href="llink2.html">second item</a></div>
                </body>
            </html>
            """
            response = HtmlResponse(url='http://example.com', body=html, encoding='utf-8')
            # hxs=Selector(response=response).xpath('//a')                    #查询所有a标签
            # hxs = Selector(response=response).xpath('//a[@id]')             #查询包含id属性的a标签
            #hxs = Selector(response=response).xpath('//a[@id="i1"]')         #查询id=i1的a标签
    
            #hxs = Selector(response=response).xpath('//a[@href="link.html"][@id="i1"]')   #查询href="link.html" &id="i1"的a标签
    
            # hxs = Selector(response=response).xpath('//a[contains(@href, "link")]')      #查询href="link.html"包含link关键字的a标签
            #hxs = Selector(response=response).xpath('//a[starts-with(@href, "link")]')    # 查询href="link.html"以link关键字开头的a标签
    
                              #使用正则匹配
            #hxs = Selector(response=response).xpath('//a[re:test(@id, "id+")]')    #查询id为 i数字  的a标签
            #hxs = Selector(response=response).xpath('//a[re:test(@id, "id+")]/text()').extract()     #/text()获取文本内容
            # hxs = Selector(response=response).xpath('//a[re:test(@id, "id+")]/@href').extract() #/@href获取href属性
    
            # hxs = Selector(response=response).xpath('/html/body/ul/li/a/@href').extract()   #python数据类型
            # hxs = Selector(response=response).xpath('//body/ul/li/a/@href').extract_first() #获取匹配到的第一个a标签
    
    
            ul_list = Selector(response=response).xpath('//body/ul/li') #支持for循环
            for item in ul_list:
                v = item.xpath('./a/span')#相对当前标签下寻找子代 ./,*/,a     #注意//遍历所有后代, /遍历所有子代
                # 或
                # v = item.xpath('a/span')
                # 或
                # v = item.xpath('*/a/span')
                print(v)
    复制代码
    复制代码
    # -*- coding: utf-8 -*-
    import scrapy,urllib.parse
    from scrapy.http import Request
    from scrapy.selector import Selector
    from scrapy.http.cookies import CookieJar
    
    
    class ChoutiSpider(scrapy.Spider):
        name = 'chouti'
        allowed_domains = ['chouti.com']
        start_urls = ['http://chouti.com/']
        cookie_dict = {}
    
        '''
        1. 发送一个GET请求,抽屉
           获取cookie
       
        2. 用户密码POST登录:携带上一次cookie
           返回值:9999
           
        3. 为为所欲为,携带cookie
        
        '''
    
        def start_requests(self):#子类重写父类的start_requests,指定其实url
            for url in  self.start_urls:
                yield Request(url,dont_filter=True,callback=self.index)
    
        def index(self,response):#首页
            cookie_jar=CookieJar() #提取本次请求的cokie,保存到cookie_jar对象
            cookie_jar.extract_cookies(response, response.request)#去响应中获取cookie
            #把cookie保存到字典
            for k, v in cookie_jar._cookies.items():
                for i, j in v.items():
                    for m, n in j.items():
                        self.cookie_dict[m] = n.value
            post_dict={
                "phone": '8613220198866',
                "password": "woshiniyeye",
                "oneMonth": 1,
            }
    
            yield Request(  #发送post请求,进行登录
                url='https://dig.chouti.com/login',
                method='POST',
                cookies= self.cookie_dict,
                headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
                body=urllib.parse.urlencode(post_dict),
    
                callback=self.login
                           )
    
        def login(self,response) :
            yield Request(url='https://dig.chouti.com/',cookies=self.cookie_dict,callback=self.get_news)
    
        def get_news(self,response):
            hxs=Selector(response)
            link_id_list=hxs.xpath('//div[@class="part2"]/@share-linkid').extract() #获取新闻ID
            for link in link_id_list:
                base_url = "http://dig.chouti.com/link/vote?linksId=%s" % (link)
                yield Request(
                        url=base_url,
                        method='POST',
                        cookies=self.cookie_dict,
                        callback=self.end_parse
                            )
        def end_parse(self,response):
            print(response.text)
    复制代码

    ---恢复内容结束---

  • 相关阅读:
    CSP-S 2020 游记
    USACO Mowing the Lawn
    洛谷 P1725 琪露诺
    浅谈单调队列
    浅谈单调栈
    洛谷 P1440 求m区间内的最小值
    POJ 2823 Sliding Window
    洛谷 P1901 发射站
    POJ 2796 Feel Good
    POJ 2559 Largest Rectangle in a Histogram
  • 原文地址:https://www.cnblogs.com/daien522556/p/10654229.html
Copyright © 2011-2022 走看看