Sam
Sam

Reputation: 23

Why do i get the error AttributeError: 'Response' object has no attribute 'type'?

i am trying to download the images from 'https://pokemondb.net/pokedex/national'.I had to open each pokemon and then save the image from there. Here is the code:

import requests, re
from bs4 import BeautifulSoup
import urllib
import requests
import shutil

#opening the websited
r=requests.get("https://pokemondb.net/pokedex/national")
c=r.content

soup=BeautifulSoup(c,"html.parser")

all=soup.find_all("span",{"class":"infocard-tall"})


for item in all:
    name = item.find("a", {"class":"ent-name"}).text
    print(name)

    #Opening onto the site for each pokemon
    #urllib.request.urlretrieve("https://img.pokemondb.net/artwork/" 
           +name.lower() + ".jpg") 

    r1 = requests.get("https://img.pokemondb.net/artwork/" + name.lower() + 
    ".jpg",
             stream=True, headers={'User-agent': 'Mozilla/5.0'})
#where i save the file to
    fileName = "D:/Desining/Neural 
     Networks/PokemonProject/artANN/PokemonANN/Images/" 
    #opening the file and saving it
    imageFile = open(fileName + name + ".jpg", 'wb')
    imageFile.write(urllib.request.urlopen(r1).read())
    imageFile.close()

I would expect the images to save to the file, however it gives me this error instead:

AttributeError                            Traceback (most recent call last)
<ipython-input-29-500d49264e5f> in <module>()
     14     #opening the file and saving it
     15     imageFile = open(fileName + name + ".jpg", 'wb')
 ---> 16     
   imageFile.write(urllib.request.urlopen(r1).response.encoding.read())
     17     imageFile.close()
     18 

d:\desining\coding\python\software\lib\urllib\request.py in urlopen(url, 
data, timeout, cafile, capath, cadefault, context)
    221     else:
    222         opener = _opener
--> 223     return opener.open(url, data, timeout)
    224 
    225 def install_opener(opener):

d:\desining\coding\python\software\lib\urllib\request.py in open(self, 
fullurl, data, timeout)
    516 
    517         req.timeout = timeout
--> 518         protocol = req.type
    519 
    520         # pre-process request

 AttributeError: 'Response' object has no attribute 'type'

I have tried updating request but it is already updated to the latest version. I have also tried using the following: urllib.request.urlretrieve(r1, fileName + name + ".jpg")

instead of:

imageFile = open(fileName + name + ".jpg", 'wb')
imageFile.write(urllib.request.urlopen(r1).read())
imageFile.close()

Thank you in advance.

Upvotes: 0

Views: 6104

Answers (1)

Ethan Henderson
Ethan Henderson

Reputation: 428

requests.get returns a response object which can be read with the content attribute. In your code you try then to open the requests response object with urlopen and then read that.

Try this on line 16 instead.

imageFile.write(r1.content)

Upvotes: 1

Related Questions