将URL请求输出写入Python中的CSV

3 投票
1 回答
3135 浏览
提问于 2025-04-18 11:57

我想把响应的内容写入一个csv文件。以下是我的代码:

import requests
from bs4 import BeautifulSoup
import csv
import time

site = 'url'

with open('receipts_10.csv', 'rU') as csvfile:
    reader = csv.reader(csvfile, delimiter=';')
    for row in reader:

        response = requests.post(site, params={'appReceiptNum':row})
        soup = BeautifulSoup(response.text)
        status = soup.find("h4")
        statusString = status.text

我已经打开了一个csv文件,现在我想用输出的内容覆盖这个csv文件:

        print(statusString)

如你所见,我现在只是把响应打印在控制台上,但我需要把它放到一个.csv文件里。有什么好主意吗?

1 个回答

0

只需要使用一个csv写入器。

像这样:

with open('receipts_10.csv', 'rU') as csvfile:
    reader = csv.reader(csvfile, delimiter=';')
    outfile = 'somefile.csv'
    ofile = open(outfile,"wb")
    writer = csv.writer(ofile,delimiter=";")

    for row in reader:       
        response = requests.post(site, params={'appReceiptNum':row})
        soup = BeautifulSoup(response.text)
        status = soup.find("h4")
        statusString = status.text
        writer.writerow(statusString)

当然,你可能需要对状态字符串进行一些格式调整,比如更改分隔符、引号或其他写入选项。可以参考Python的csv库文档来帮助你。但这就是基本的原则。

如果你实际上并不从csv文件中读取任何内容,那你当然不需要读取器。

撰写回答