栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

scrapy 的入门使用超级详细

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

scrapy 的入门使用超级详细

记录一下scrapy的安装和实践操作的流程

 

1.安装
pip install Scrapy
2.创建scrapy项目 

project是蜘蛛名字

scrapy startproject project
3.创建scrapy   res.py  蜘蛛文件  

保存在spiders目录下

4.查看是否可正常访问网站

​scrapy shell http://lab.scrapyd.cn

看到response 返回200 说明此网站支持爬虫 

5.命令行测试 dom 元素内容

查找元素:我们要查找文案、作者、标签

可以看到下面的图片中展示了此页面的dom元素结构,所有的文字列表都保存在id为main的div元素中,我们将其提取出来

// 执行代码
response.xpath('//div[@id="main"]').extract()

 得到以下结果,“”注意“” 这里得出来的是一个数组,为id为main标签下的所有数据

按照此方法 我们就能依次得到文案、作者、标签、页码

// 文案 text  类型str
response.xpath('span[@]/text()').extract_first()

// 作者 text  类型str
response.xpath('span/small/text()').extract_first()

// 标签 text  类型arr
response.xpath('div/a/text()').extract()

// 页码
response.xpath('//ol[@]/li/a'[1].xpath('./@href').extract_first()

6.编写代码

1.items.py

import scrapy

class resItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    # list = response.xpath('//div[@id="main"]/div')

    # 短文 str list[0].xpath('span[@]/text()').extract_first()
    short =  scrapy.Field()  
    
    # 作者 str list[0].xpath('span/small/text()').extract_first()
    author = scrapy.Field()  
     
    # 标签 arr list[0].xpath('div/a/text()').extract()
    tags = scrapy.Field()  

2.编写spiders目录下的蜘蛛文件 res.py

import scrapy

from tutorial.items import resItem

# 声明页码
pageNum = 0


class itemSpider(scrapy.Spider):
    # 定义spider的名字
    name = 'listSpider'

    # 从哪个页面开始
    start_urls = ['http://lab.scrapyd.cn']

    def parse(self, response):
        # 声明全局变量
        global pageNum

        list = response.xpath('//div[@id="main"]/div')

        for v in list:
            item = resItem()
            # 短文 str
            short = v.xpath(
                'span[@]/text()').extract_first()
            item['short'] = v.xpath(
                'span[@]/text()').extract_first()

            # 作者 str
            autor = v.xpath('span/small/text()').extract_first()
            item['author'] = v.xpath('span/small/text()').extract_first()

            # 标签 arr
            tag = (v.xpath('div/a/text()').extract())
            tags = ','.join(tag)
            item['tags'] = ','.join(tag)  # 数组转换为字符串

            fileName = '%s-语录.txt' % autor  # 定义文件名,如:木心-语录.txt

            with open(fileName, "a+") as f:  # 不同人的名言保存在不同的txt文档,“a+”以追加的形式
                f.write(short)
                f.write('n')  # ‘n’ 表示换行
                f.write('标签:' + tags)
                f.write('n-------n')
                f.close()

            yield item

        pageNum += 1
        if pageNum <= 5:
            # 获取下一页的链接
            new_link = response.xpath(
                '//ol[@]/li/a')[pageNum].xpath('./@href').extract_first()
            # 再次请求下一个页面
            yield scrapy.Request(new_link, callback=self.parse, dont_filter=True)
            print('pageNum:', pageNum)

3.编写pipelines.py 文件 (该文件负责将爬取到的信息写入(数据库,设备,控制台等))

class TutorialPipeline:
    
    # 此处的item 就是蜘蛛 yield 的item
    def process_item(self, item, spider):
        
        print('short',item['short'])
        print('author',item['author'])
        print('tags',item['tags'])
        
        # return item

4.修改settings.py文件

 7.执行爬虫操作

进入蜘蛛文件夹下执行命令

scrapy crawl listSpider

得到保存的文件说明成功爬虫

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/350042.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号