保存对文本文件的响应

时间:2018-04-09 21:38:24

标签: python-3.x scrapy python-requests scrapy-spider

我正在尝试创建2个文件。首先,回应.png(有效)。其次,取所有html并保存到文本。将html保存到文本文件只显示为空白。

def parse_request(self, response):

    # Works and saves file and png
    with open('image.png', 'wb') as f:
        f.write(response.body)

    # Creates file but doesnt have any text in it
    with open('text.txt', 'wb') as f:
        f.write(response.body.decode("utf-8"))

1 个答案:

答案 0 :(得分:0)

您是否尝试将response.body存储到变量,然后write该变量?

我认为你在第一次阅读时耗尽了流的反应。我也猜测你可能存储整个响应,而不仅仅是image.png文件中的png。

def parse_request(self, response):
    body = response.body
    # Works and saves file and png
    with open('image.png', 'wb') as f:
        f.write(body)

    # Creates file but doesnt have any text in it
    with open('text.txt', 'wb') as f:
        f.write(body.decode("utf-8"))