zoukankan      html  css  js  c++  java
  • Python Scrapy框架

    1.安装Scrapy框架

    在目录下进入命令行,输入以下安装Scrapy框架命令

    pip install Scrapy

    2.创建Scrapy项目

    在所在文件夹的路径下进入命令行,输入以下命令

    scrapy startproject 项目名称

    3.定义项目中的Item

    import scrapy
    
    class DmozItem(scrapy.Item):
        # title = scrapy.Field()
        # link = scrapy.Field()
        # desc = scrapy.Field()

    4.创建爬虫脚本

    scrapy genspider 爬虫文件名称 爬虫的域名

    5.执行爬取

    进入项目的根目录,执行下列命令启动spider

    scrapy crawl dmoz

    6.提取Item

    这里给出XPath表达式的例子及对应的含义

    /html/head/title: 选择HTML文档中 <head> 标签内的 <title> 元素
    /html/head/title/text(): 选择上面提到的 <title> 元素的文字
    //td: 选择所有的 <td> 元素
    //div[@class="mine"]: 选择所有具有 class="mine" 属性的 div 元素

    7.提取数据

    编辑爬虫脚本

    import scrapy
    
    class DmozSpider(scrapy.Spider):
        name = "dmoz"
        allowed_domains = ["dmoz.org"]
        start_urls = [
            "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
            "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
        ]
    
        def parse(self, response):
            for sel in response.xpath('//ul/li'):
                title = sel.xpath('a/text()').extract()
                link = sel.xpath('a/@href').extract()
                desc = sel.xpath('text()').extract()
                print title, link, desc

    8.保存数据

    scrapy保存信息的最简单的方法主要有四种,-o 输出指定格式的文件,命令如下:

    scrapy crawl 爬虫名称 -o 生成的数据文件名称

    json lines格式,默认为Unicode编码

    scrapy crawl 爬虫名称 -o 生成的数据文件名称

    csv 逗号表达式,可用Excel打开

    scrapy crawl 爬虫名称 -o 生成的数据文件名称

    xml格式

    scrapy crawl 爬虫名称 -o 生成的数据文件名称
  • 相关阅读:
    .NET Framework类库大概
    CTS、CLS、CIL与CLR
    .NETFramework、CLR、.NET Framework class library、托管代码是什么
    万维网三大核心技术
    Clang、GCC和LLVM是什么
    常见开源许可证、开源协议GPL、BSD、MIT、Mozilla、Apache和LGPL之间区别
    编译原理之变量、名字与标识符
    编译原理之静态策略与动态策略
    Jupyter Notebook打开任意文件
    修改VsCodes的语言为中文
  • 原文地址:https://www.cnblogs.com/alanlee1473/p/15034246.html
Copyright © 2011-2022 走看看