这是我的代码:
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/