当前位置: 首页 > 后端技术 > Python

爬虫系列:保存CSV文件

时间:2023-03-25 20:05:49 Python

本期将讲解如何将数据保存为CSV文件。逗号分隔值(Comma-SeparatedValues,CSV,有时也称为字符分隔值,因为分隔符也可以不是逗号)是一种常用的存储表格数据的文件格式。MicrosoftExcel和许多应用程序都支持CSV格式,因为它很简单。下面是一个CSV文件的例子:code,parentcode,level,name,parentcodes,province,city,district,town,pinyin,jianpin,firstchar,tel,zip,lng,lat110000,100000,1,Beijing,110000,北京,,,,北京,BJ,B,,,116.405285,39.904989110100,110000,2,北京,"110000,110100",北京,北京,,,北京,BJS,B,010,100000,116.405285,39,1901981,3,DongchengDistrict,"110000,110100,110101",Beijing,Beijing,DongchengDistrict,,Dongcheng,DCQ,D,010,100000,116.418757,39.917544和Python一样,CSV中的空格也很重要:每行分隔由换行符分隔,列由逗号分隔(因此名称为“逗号分隔值”)。CSV文件也可以使用制表符或其他字符来分隔行,但这种情况不太常见,用得也不多。如果你只是想将网页中的CSV文件不作任何修改和分析,直接下载到电脑上,那么请不要看下面的内容,直接使用上一篇介绍的方法下载并保存CSV文件即可。.Python的CSV库可以轻松修改CSV文件,甚至可以从头开始创建CSV文件:')如果不是path.exists(get_path):os.makedirs(get_path)csv_file=open(get_path+'\\test.csv','w+',newline='')try:writer=csv.writer(csv_file)writer.writerow(('number','numberplus2','numbertimes2'))foriinrange(10):writer.writerow((i,i+2,i*2))最后:csv_file。close()if__name__=='__main__':DataSaveToCSV().save_data()如果文件文件夹不存在,创建一个新文件夹。如果该文件已经存在,Python将用新数据覆盖test.csv文件,newline=''删除行之间的空格。运行后会看到一个CSV文件:number,number加2,number乘以20,2,01,3,22,4,43,5,64,6,85,7,106,8,127,9,148,10,169,11,18以下示例是收集一篇博客文章并将其存储在CSV文件中。具体代码如下:importcsvimportosfromosimportpathfromutilsimportconnection_utilfromconfigimportlogger_configclassDataSaveToCSV(object):def__init__(self):self._init_download_dir='downloaded'self._target_url='https://www.scrapingbee.com/blog/'self._baseUrl='https://www.scrapingbee.com'self._init_connection=connection_util.ProcessConnection()logging_name='write_csv'init_logging=logger_config.LoggingConfig()self._logging=init_logging.init_logging(logging_name)defscrape_data_to_csv(self):get_path=path.join(os.getcwd(),'files')如果不是path.exists(get_path):os.makedirs(get_path)withopen(get_path+'\\article.csv','w+',newline='',encoding='utf-8')作为csv_file:writer=csv.writer(csv_file)writer.writerow(('title','releasetime','contentsummary'))#连接到目标网站并获取内容get_content=self._init_connection.init_connection(self._target_url)ifget_content:parent=get_content.findAll("section",{"class":"section-sm"})[0]get_row=parent.findAll("div",{"class":"col-lg-12mb-5mb-lg-0"})[0]get_child_item=get_row.findAll("div",{"class":"col-md-4mb-4"})foriteminget_child_item:#获取标题文本get_title=item.find("a",{"class":"h5d-blockmb-3post-title"}).get_text()#获取发布日期get_release_date=item.find("div",{"class":"mb-3mt-2"}).findAll("span")[1].get_text()#获取文章描述get_description=item.find("p",{"class":"card-textpost-description"}).get_text()writer.writerow((get_title,get_release_date,get_description))else:self._logging.warning('没有获取到文章内容,请检查!')if__name__=='__main__':DataSaveToCSV().scrape_data_to_csv()大部分代码复用了之前文章的内容,这里需要强调的是:logging_name='write_csv'init_logging=logger_config.LoggingConfig()self._logging=init_logging.init_logging(logging_name)设置日志名称并实例化日志,用于后续的日志记录,用open(get_path+'\\article.csv','w+',newline='',encoding='utf-8')ascsv_file:with()定义执行with语句时要建立的运行时上下文。with()允许封装正常的try...except...finally使用模式以便于重用。newline=''防止CSV文件中的行之间出现空行。同时文件的编码也设置为utf-8。这样做的目的是为了避免包含中文或其他语言的文件出现乱码。以上是关于将收集到的内容保存为csv文件。这个例子的所有代码都托管在github上。github:https://github.com/sycct/Scra...如有任何问题,欢迎在github上issue。