2023年6月29日发(作者:)
Python爬⾍中创建⽂件并传⼊数据,实现标题和url持久化1.爬取博客园中每条新闻的标题和url,在中写⼊操作内容import scrapyimport sysimport iofrom..items import cnlogsItemfrom or import = Wrapper(,encoding="utf-8")class CnblogsSpider(): name = 'cnblogs' allowed_domains = [''] start_urls = ['/'] def parse(self, response): line = Selector(response=response).xpath('//div[@id="post_list"]//div[@class="post_item_body"]') # href = Selector(response=response).xpath('//div[@id="post_list"]//div[@class="post_item_body"]/h3/a[@class="titlelnk"]/@href').extract() items = [] for node in line: title = ('./h3/a[@class="titlelnk"]/text()').extract() href = ('./h3/a[@class="titlelnk"]/@href').extract() item_obj = cnlogsItem(title=title,href=href) #把suthor、href封装成⼀个对象 item_obj['title']=title[0] item_obj['href']=href[0] #将item对象传递给pipeline yield item_objimport scrapyclass cnlogsItem(): # item()⽅法:把字典中每对key和value组成⼀个元组,并把这些元组放在列表中返回。 # define the fields for your item here like: title = () href = () #item做格式化3.要想调⽤,⾸先必须要在中配置pipelineITEM_PIPELINES = { 'yuanPipeline': 300,}4.编写pipeline⽂件,创建的⽂件,并将数据传⼊⽂件中import jsonclass PabokeyuanPipeline(object): def open_spider(self,spider): = open('','wb') #创建⼀个的⽂件 def process_item(self, item, spider): # print(spider,item) #spider是爬⾍,输出的是哪个爬⾍ tpl = "%sn%snn"%(item['title'],item['href']) (("utf-8")) #将tpl中的内容写⼊⽂件中 return item def close_spider(self,spider): ()5.在cmd中执⾏E:pycharmpabokeyuan>scrapy crawl cnblogs --nolog6.在⽂件⽬录下可以看到⽂件,打开该⽂件就会看到以下内容⼀个低级错误引发Netty编码解码中⽂异常/throwable/p/thon基础(⼗四)/tianlangdada/p/死磕 java同步系列之zookeeper分布式锁/tong-yuan/p/e技术研究-.NET Core迁移前的准备⼯作/tianqing/p/ring Cloud Config 配置中⼼实践过程中,你需要了解这些细节!/ldws/p/ring Environment的加载/cxyAtuo/p/cel VBA⼊门(⼗)⽤户窗体开发/wuzhiblog/p/vba_从⼆叉查找树到B+树中间的各种树/godoforange/p/免费下载 80多种的微软推出⼊门级 .NET视频/shanyou/p/#C# 中的Task创建指南/chasingdreams2017/p/acle 查询真实执⾏计划/kingsleylam/p/中⽂分词/sandwichnlp/p/va中Synchronized的优化原理/death00/p/分布式任务调度平台XXL-JOB/wmyskxz/p/深⼊探究js中的隐式变量声明/yukixing/p/ring启动流程/cxyAtuo/p/oKeeper单机服务端的启动源码阅读/ZhuChangwu/p/PR 2019 论⽂解读 | ⼩样本域适应的⽬标检测/ManWingloeng/p/使⽤.net core3.0 正式版创建Winform程序/wuhuacong/p/ring Boot 整合 Web 开发/5Dylan/p/
发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1687985338a63889.html
评论列表(0条)