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

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

我正在尝试从“https://pokemondb.net/pokedex/national”下载图像。我必须打开每个口袋妖怪,然后从那里保存图像。这是代码:

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

我希望图像能保存到文件中,但它却给我这个错误:

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'

我已经尝试更新请求,但它已经更新到最新版本。我也尝试过使用以下内容: urllib.request.urlretrieve(r1, fileName + name + ".jpg")

而不是:

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

提前致谢。

requests.get returns 一个可以用内容属性读取的响应对象。在您的代码中,您尝试使用 urlopen 打开请求响应对象,然后读取它。

改为在第 16 行试试这个。

imageFile.write(r1.content)