当前位置: 代码网 > it编程>前端脚本>Python > Python Scrapy框架开发:通过pipelines模块将数据写入记事本

Python Scrapy框架开发:通过pipelines模块将数据写入记事本

2026年09月11日 Python 我要评论
理论知识:用于处理spider中获取的items,可以对获取的数据进行进一步处理(将获取的items保存至文件或者数据库等)如果要使用pipelines模块中定义的各pipelines类,必须在set

理论知识:

用于处理spider中获取的items,可以对获取的数据进行进一步处理(将获取的items保存至文件或者数据库等)如果要使用pipelines模块中定义的各pipelines类,必须在settings模块中指定,格式如下:pipeline的权重值越小优先级越高

代码部分:

1. 创建一个新的项目  test1  命令:scrapy startproject test1

2. 重写items.py文件,定义title属性

import scrapy
class test1item(scrapy.item):
    # define the fields for your item here like:
    # name = scrapy.field()
    title=scrapy.field()

3. 修改setting文件,指定要使用的pipeline对应的类。将下面这行代码解注释

item_pipelines = {
   "test1.pipelines.mytest": 300,
}

4. 在spider目录下创建爬虫文件myspider.py   命令:scrapy genspider -t basic myspider baidu.com

import scrapy
from test1.items import test1item
class myspiderspider(scrapy.spider):
    name = "myspider"
    allowed_domains = ["sina.com.cn"]
    start_urls = ["http://sina.com.cn/"]
    def parse(self, response):
        item = test1item()
        item['title'] = response.xpath("/html/head/title").extract_first()
        print(item['title'])
        yield item

5. 重写pipeline.py文件

import codecs
class mytest(object):
    def __init__(self):
        self.file = codecs.open("c:/users/administrator/lxj/test.txt","wb",encoding="utf-8")
    def process_item(self, item, spider):
        ll=str(item)+'\n'
        self.file.write(ll)
        return item
    def close_spider(self,spider):
        self.file.close()

6. 执行行爬虫文件 命令:scrapy crawl myspider --nolog

到此这篇关于python scrapy框架开发:通过pipelines模块将数据写入记事本的文章就介绍到这了,更多相关scrapy框架将数据写入内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com