Python:AttributeError:Response.read 和 .text 不起作用

标签 python python-requests attributeerror

这是我的代码:

import requests

feeds = []

for i in range(2002, 2023):
    feeds.append(str(i))

for feed in feeds:
    link = f"https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-{feed}.json.zip"
    response = requests.get(link)
    if response.status_code == 200:
        print("Success")
        with open(f"{feed}.zip", "wb") as f:
            f.write(response.read())

但是,当我在最后一行使用 response.read() 时,它给了我这个错误:

Traceback (most recent call last):
  File "c:\Users\30kal\database.py", line 48, in <module>
    f.write(response.read())
AttributeError: 'Response' object has no attribute 'read'

但是,当我尝试使用 response.text 时,它给了我这个错误:

Traceback (most recent call last):
  File "c:\Users\30kal\database.py", line 48, in <module>
    f.write(response.text)
TypeError: a bytes-like object is required, not 'str'

知道为什么吗?

最佳答案

您收到两个具有不同原因的错误。

出现第一种情况是因为 requests.get 返回的类型 requests.models.Response 没有函数 read

发生第二种情况是因为当您使用选项“wb”打开文件时无法将 str 类型写入文件;表示您要以“写入二进制”模式打开文件,该模式仅接受类似字节的对象,而不接受字符串。

我查看了Download Returned Zip file from URL对您的代码进行此修改:

import requests

feeds = map(str,range(2002, 2023))


for feed in feeds:
    link = f"https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-{feed}.json.zip"
    response = requests.get(link, stream=True)
    if response.status_code == 200:
        print("Success")
        with open(f"{feed}.zip", "wb") as f:
            for chunk in response.iter_content(chunk_size=512):
                if chunk:  # filter out keep-alive new chunks
                    f.write(chunk)

您可以查看替代方案的链接。

关于Python:AttributeError:Response.read 和 .text 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72889820/

相关文章:

python - 使用带通配符的键创建 Python 字典

python - 与 Celery 任务共享 Pyramid 的数据库 session

python - 解析\在命令行参数 - python 2.7.3

python - 在 python 中发出 get 请求时不断收到 SSL 错误

python - 使用 Flask 创建注册表单 - AttributeError : 'ValueError' object has no attribute 'name'

python-3.7 - Oandapy API 上的属性错误

python - Openpyxl 次要网格线

python - python 中的网页抓取、正则表达式和迭代

python - 如何从帖子请求中拆分正文

返回 AttributeError : __enter__ 的 Python Json