【问题标题】:Why do i get the error AttributeError: 'Response' object has no attribute 'type'?为什么我会收到错误 AttributeError: 'Response' object has no attribute 'type'?
【发布时间】:2017-12-05 08:04:59
【问题描述】:

我正在尝试从“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()

提前谢谢你。

【问题讨论】:

    标签: python web-scraping python-requests urllib


    【解决方案1】:

    requests.get 返回一个可以使用 content 属性读取的响应对象。在您的代码中,您尝试使用 urlopen 打开请求响应对象,然后阅读该对象。

    在第 16 行试试这个。

    imageFile.write(r1.content)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2022-12-27
      • 1970-01-01
      • 2020-05-26
      • 2016-11-04
      相关资源
      最近更新 更多