scrapy学习记录|青训营笔记

94 阅读1分钟

这是我参加[第四届青训营]笔记创作活动的第7天。

1、scrapy流程

image.png

image.png

2、scrapy各个模块的具体作用

image.png

3、安装以及使用

image.png

image.png

4、创建爬虫

image.png 在d:/work/myspider/myspider中执行命令

5、开始爬取

在项目目录中输入 scrap crawl <爬虫名字>

6、完成爬虫

(1)修改起始的爬虫 (2)检查允许修改的域名 (3)在parse中实现爬取逻辑

image.png

image.png

7、保存数据

image.png

8、数据建模 定义item即提前规划好哪些字段需要抓取,防止手误,因为定义好之后,在运行过程中,系统会自动检查

`import scrapy from myspider.items import MyspiderItem

class ItcastSpider(scrapy.Spider): name = 'itcast' allowed_domains = ['itcast.cn'] start_urls = ['www.itcast.cn/channel/tea…']

def parse(self, response):
    #定义对于网站的相关操作
    #pass
    #解析方法,通常用于起始url的response处理
    #with open('itcast.html','wb') as f:
        #f.write(response.body)
    node_list = response.xpath('//div[@class="li_txt"]')
    #print(len(node_list))
    for node in node_list:
        #temp={}
        item=MyspiderItem
        #xpath方法返回的是选择器对象类型,extract()用于从选择器对象中提取数据
        item['nmae']=node.xpath('./h3/text()')[0].extract()
        
        item['title']=node.xpath('./h4/text()')[0].extract()
        item['desc']=node.xpath('./p/text()')[0].extract()
        #xpath结果为只含有一个值的列表,可以使用extract_first()
        
        yield item
        #传递数据,但是不会停止函数
        `
        
        
        
        

`# Define your item pipelines here

Don't forget to add your pipeline to the ITEM_PIPELINES setting

See: docs.scrapy.org/en/latest/t…

useful for handling different item types with a single interface

from itemadapter import ItemAdapter import json

class MyspiderPipeline:

def __init__(self):
    self.file = open('itcast.json','w')



def process_item(self, item, spider):
    #print('itcast:',item)
    #默认使用完管道之后需要将数据返回给引擎
    #/将item对象强转为字典
    item=dict(item)
    #将字典数据序列化
    json_data=json.dumps(item,ensure_ascii=False)+',\n'
    #将数据写入文件
    self.file.write(json_data)
    return item

def __del__(self):
    self.file.close()`