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 生成的数据文件名称

 

posted @ 2021-07-20 12:12  Alan-lee  阅读(147)  评论(0编辑  收藏  举报