关于python:爬虫系列存储-CSV-文件

3次阅读

共计 3308 个字符,预计需要花费 9 分钟才能阅读完成。

本期将解说如果将数据保留到 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/Scra…

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

正文完
 0