【问题标题】:Save scraping results one by one into Excel or CSV file in Python将抓取结果一一保存到 Python 中的 Excel 或 CSV 文件中
【发布时间】:2020-07-10 08:26:56
【问题描述】:

我有一个爬虫代码如下:

import requests
import json
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import re
from datetime import datetime

def crawl(id):
    try:
        url = 'https://www.china0001.com.cn/project/{0:06d}.html'.format(id)
        print(url)
        content = requests.get(url).text
        soup = BeautifulSoup(content, 'lxml')
        tbody = soup.find("table", attrs={"id":"mse_new"}).find("tbody", attrs={"class":"jg"})
        tr = tbody.find_all("tr")
        rows = []
        for i in tr[1:]:
            rows.append([j.text.strip() for j in i.findAll("td")])
        out = dict([map(str.strip, y.split(':')) for x in rows for y in x])
        return out

    except AttributeError:
        return False

data = list()
for id in range(699998, 700010):
    print(id)
    res = crawl(id)
    if res:
        data.append(res)

if len(data) > 0:
    df = pd.DataFrame(data)
    df.to_excel('test.xlsx', index = False)

在这段代码中,整个抓取过程完成后,结果数据框df将被写入Excel文件。

现在我想在抓取过程中将抓取结果一一保存到Excel或CSV文件中,请问如何修改上面的代码?

谢谢。

更新:

MAX_WORKERS = 30
ids = range(700000, 700050)
workers = min(MAX_WORKERS, len(ids))

with futures.ThreadPoolExecutor(workers) as executor:
    res = executor.map(crawl, sorted(ids))

data = list(res)

if len(data) > 0:
    df = pd.DataFrame(data)
    df.to_csv('test.csv', mode = 'a', header = True, index = False)

【问题讨论】:

    标签: python-3.x pandas web-scraping web-crawler


    【解决方案1】:

    尝试将to_csvheader=False, index=False 一起使用

    例如:

    for id in range(699998, 700010):
        res = crawl(id)
        if res:
            df = pd.DataFrame([res])
            df.to_csv('test.csv', mode='a', header=False, index=False)
    

    【讨论】:

    • 对不起,我收到一个错误:TypeError: to_excel() got an unexpected keyword argument 'mode'
    • 抱歉,该选项仅在.csv 中可用,对于需要使用startrow 的excel
    • 所以,我需要使用df.to_csv('test.csv', mode='a', header=False, index=False),对吧?
    • 我尝试将您的代码应用于多进程抓取,但它会引发错误AttributeError: 'bool' object has no attribute 'keys',您能看看我的问题的更新吗?非常感谢。
    【解决方案2】:

    我建议在这里查看我的问题: What is the problem with the pandas to csv in my code?。 我建议查看每日工作表的答案,然后应用并修改它以适合您的程序

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-02
      • 2016-08-06
      • 1970-01-01
      • 2021-10-31
      • 2017-05-01
      • 2011-03-21
      • 2019-03-25
      • 2013-09-30
      相关资源
      最近更新 更多