qiweunvjah
qiweunvjah

Reputation: 142

Python: AttributeError: Response.read and .text not working

Here is my code:

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())

However, when I use response.read() on the last line, it gives me this error:

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'

But, when I try to use response.text, it gives me this error:

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'

Any idea why?

Upvotes: 2

Views: 953

Answers (1)

Bob th
Bob th

Reputation: 286

You are getting two errors with different causes.

The first occurs because the type requests.models.Response that requests.get returns does not have a function read.

The second occurs because you can't write a str type to a file when you open it with the option "wb"; that indicates you want to open the file with "write binary" mode, which only accepts bytes-like objects, not strings.

I looked at Download Returned Zip file from URL to make this modification to your code:

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)

You could take a look at the link for alternatives.

Upvotes: 2

Related Questions