我正在尝试从'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()
提前谢谢。
答案 0 :(得分:1)
requests.get
返回一个响应对象,可以使用content属性读取该对象。在您的代码中,您尝试使用urlopen打开请求响应对象,然后读取它。
请在第16行尝试此操作。
imageFile.write(r1.content)