• scrapy框架的基础使用流程


    前提是安装好各种准备库。

    1.新建一个工程

    在终端输入:scrapy startprojetc 你的项目名, 和django比较类似

    # scrapy.cfg  项目的主配置信息
    # items.py 设置数据存储模版,用于结构化数据
    # pipelines.py  数据持久化处理
    # settings.py 配置文件
    # spiders 爬虫的目录

    2.在目录下创建一个爬虫文件

       2.1 在终端切换到工程目录,然后输入:scrapy genspider 爬虫文件的名称 起始url

    创建好后会自动给你包含如下的代码的文件

    # -*- coding: utf-8 -*-
    import scrapy
    
    
    class FirstfileSpider(scrapy.Spider):
        name = 'firstfile'
        allowed_domains = ['www.xiushibaike.com']
        start_urls = ['http://www.xiushibaike.com/']
    
        def parse(self, response):
            pass

    所有的爬虫类都会继承这个Spider类,name是对应爬虫文件的名称(在多个爬虫文件中),allowed_domains是允许的域名,只可以爬取指定域名下的页面数据,也可以指定多个域名。start_urls是起始url,表示当前工程将要爬取的页面url,注意要符合前面的允许的域名。最后的parse函数是对获取的页面数据指定内容的解析。response参数指的的拿到的响应对象。注意parse方法的返回值必须为迭代器或者空。

    3.对应的文件中编写爬虫的功能程序

    4.配置文件的编写

    刚开始使用时settings.py文件就注意两个参数,USER_AGENT爬虫身份伪装(就是那个headers中的USER-Agent),ROBOSTXT_OBEY表示是否遵守RobotTxt协议。

    5.执行代码

    终端中输入命令:scrapy crawl 文件名

    简单的示例:爬取嗅事百科段子作者与内容。

    # -*- coding: utf-8 -*-
    import scrapy
    
    
    class FirstfileSpider(scrapy.Spider):
        name = 'firstfile'
        # 这个一般不用
        # allowed_domains = ['www.qiushibaike.com']
        start_urls = ['https://www.qiushibaike.com/text/']
    
        def parse(self, response):
    
            # 使用框架的xpath接口
            list_div = response.xpath('//div[@id="content-left"]/div')
            for div in list_div:
                author = div.xpath("./div/a[2]/h2/text()").extract()[0]
                content = div.xpath("./a/div/span/text()").extract()[0]
                print(author)
                print(content)
    
  • 相关阅读:
    QT内置的ICON资源
    Spark源代码阅读笔记之MetadataCleaner
    Android API Guides---Bluetooth
    做一个WINDOWS下破解WIFI。不须要Linux抓包!
    CPU GPU设计工作原理《转》
    杭电 1280 前m大的数
    机房收费系统——报表(2)
    概览C++之const
    Android动态禁用或开启屏幕旋转工具
    shrink-to-fit(自适应宽度)
  • 原文地址:https://www.cnblogs.com/haoqirui/p/10671240.html
Copyright © 2020-2023  润新知