爬虫系列:存储 CSV 文件

简介: 爬虫系列:存储 CSV 文件

上一期:爬虫系列:存储媒体文件,讲解了如果通过爬虫下载媒体文件,以及下载媒体文件相关代码讲解。

本期将讲解如果将数据保存到 CSV 文件。

逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号)是存储表格数据常用文件格式。Microsoft Excel 和很多应用都支持 CSV 格式,因为它很简洁。下面是一个 CSV 文件的例子:

code,parentcode,level,name,parentcodes,province,city,district,town,pinyin,jianpin,firstchar,tel,zip,lng,lat
110000,100000,1,北京,110000,北京,,,,Beijing,BJ,B,,,116.405285,39.904989
110100,110000,2,北京市,"110000,110100",北京,北京市,,,Beijing,BJS,B,010,100000,116.405285,39.904989
110101,110100,3,东城区,"110000,110100,110101",北京,北京市,东城区,,Dongcheng,DCQ,D,010,100000,116.418757,39.917544

和 Python 一样, CSV 里留白(whitespace)也是很重要的:每一行都用一个换行符,列与列之间用逗号分隔(因此也叫“逗号分隔值”)。CSV 文件还可以用 Tab 字符或其他字符分隔行,但是不太常见,用得不多。

如果你只想从网页上把 CSV 文件下载到电脑里,不打算做任何修改和解析,那么接下来的内容就不要看了,只用上一篇文章介绍的方法下载并保存 CSV 文件就可以了。

Python 的 CSV 库可以非常简单的修改 CSV 文件,甚至从零开始创建一个 CSV 文件:

import csv
import os
from os import path

class DataSaveToCSV(object):

@staticmethod
def save_data():
    get_path = path.join(os.getcwd(), 'files')
    if not 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', 'number plus 2', 'number times 2'))
        for i in range(10):
            writer.writerow((i, i + 2, i * 2))
    finally:
        csv_file.close()

if name == '__main__':

DataSaveToCSV().save_data()

如果 files 文件夹不存在,新建文件夹。如果文件已经存在,Python 会用新的数据覆盖 test.csv 文件,newline='' 去掉行与行之间得空格。

运行完成之后,你会看到一个 CSV 文件:

number,number plus 2,number times 2
0,2,0
1,3,2
2,4,4
3,5,6
4,6,8
5,7,10
6,8,12
7,9,14
8,10,16
9,11,18
下面一个示例是采集某博客文章,并存储到 CSV 文件中,具体代码如下:

import csv
import os
from os import path

from utils import connection_util
from config import logger_config

class DataSaveToCSV(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)


def scrape_data_to_csv(self):
    get_path = path.join(os.getcwd(), 'files')
    if not path.exists(get_path):
        os.makedirs(get_path)
    with open(get_path + '\\article.csv', 'w+', newline='', encoding='utf-8') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(('标题', '发布时间', '内容概要'))
        # 连接目标网站,获取内容
        get_content = self._init_connection.init_connection(self._target_url)
        if get_content:
            parent = get_content.findAll("section", {"class": "section-sm"})[0]
            get_row = parent.findAll("div", {"class": "col-lg-12 mb-5 mb-lg-0"})[0]
            get_child_item = get_row.findAll("div", {"class": "col-md-4 mb-4"})
            for item in get_child_item:
                # 获取标题文字
                get_title = item.find("a", {"class": "h5 d-block mb-3 post-title"}).get_text()
                # 获取发布时间
                get_release_date = item.find("div", {"class": "mb-3 mt-2"}).findAll("span")[1].get_text()
                # 获取文章描述
                get_description = item.find("p", {"class": "card-text post-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)

设置日志名称,并实例化日志,用于后面记录日志。

with open(get_path + '\\article.csv', 'w+', newline='', encoding='utf-8') as csv_file:

with() 定义了在执行 with 语句时要建立的运行时上下文。with() 允许对普通的 try...except...finally 使用模式进行封装以方便地重用。

newline='' 避免在 CSV 文件中行与行之间空行内容产生。

同时也设置了文件的编码为 utf-8 ,这样做的目的是避免文件含有中文或者其他语言造成乱码。

以上就是关于将采集的内容保存为 csv 文件的内容,本实例的所有代码托管于 github。

github: https://github.com/sycct/Scrape_1_1.git

如果有任何问题,欢迎在 github issue。

相关文章
|
1月前
|
存储 NoSQL MongoDB
Python爬虫之非关系型数据库存储#5
MongoDB、Redis【2月更文挑战第18天】
46 1
|
1月前
|
数据采集 存储 Web App开发
一键实现数据采集和存储:Python爬虫、Pandas和Excel的应用技巧
一键实现数据采集和存储:Python爬虫、Pandas和Excel的应用技巧
|
1月前
|
SQL 关系型数据库 MySQL
Python爬虫之关系型数据库存储#5
python MySQL 增删改查操作【2月更文挑战第17天】
31 1
|
1月前
|
存储 数据采集 NoSQL
Python爬虫存储库安装#1
摘要:PyMySQL安装、PyMongo安装、redis-py安装、RedisDump安装【2月更文挑战第4天】
80 4
|
9月前
|
数据采集 自然语言处理 Java
爬虫系统的核心:如何创建高质量的HTML文件?
在网页抓取或爬虫系统中,HTML文件的创建是一项重要的任务。HTML文件是网页的基础,包含了网页的所有内容和结构。在爬虫系统中,我们需要生成一个HTML文件,以便于保存和处理网页的内容。
|
数据采集 存储 编解码
「Python」爬虫-5.m3u8(视频)文件的处理
>本文主要讲解了如何下载m3u8的视频文件到本地,加密解密,将ts文件合并为一个mp4文件三个知识点。
460 0
|
11月前
|
存储 数据采集 NoSQL
爬虫数据存储技术比较:数据库 vs. 文件 vs. NoSQL
爬虫数据存储技术比较:数据库 vs. 文件 vs. NoSQL
|
数据采集 Python
Python爬虫:使用requests库下载大文件
Python爬虫:使用requests库下载大文件
343 0
|
存储 数据采集 Oracle
爬虫系列:使用 MySQL 存储数据
爬虫系列:使用 MySQL 存储数据
142 0
爬虫系列:使用 MySQL 存储数据
|
数据采集 TensorFlow 算法框架/工具
Dataset之MNIST:MNIST(手写数字图片识别+ubyte.gz文件)数据集的下载(基于python语言根据爬虫技术自动下载MNIST数据集)
Dataset之MNIST:MNIST(手写数字图片识别+ubyte.gz文件)数据集的下载(基于python语言根据爬虫技术自动下载MNIST数据集)