我正在尝试编写一个可下载google图片的python文件,但出现以下错误
“ C:\ Users \ marco \ Desktop \ Scripts Python \ venv \ Scripts \ python.exe”“ C:/ Users / marco / Desktop / Scripts Python / ChatBot.py” 追溯(最近一次通话): 文件“ C:/ Users / marco / Desktop / Scripts Python / ChatBot.py”,第4行,在 从urllib导入FancyURLopener ImportError:无法从'urllib'(C:\ Users \ marco \ AppData \ Local \ Programs \ Python \ Python37-32 \ lib \ urllib__init __。py)中导入名称'FancyURLopener'
我的代码:
import os
import sys
import time
from urllib import FancyURLopener
import urllib2
import simplejson
# Define search term
searchTerm = "william shatner"
# Replace spaces ' ' in search term for '%20' in order to comply with request
searchTerm = searchTerm.replace(' ','%20')
# Start FancyURLopener with defined version
class MyOpener(FancyURLopener):
version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
myopener = MyOpener()
# Set count to 0
count= 0
for i in range(0,10):
# Notice that the start changes for each iteration in order to request a new set of images for each loop
url = ('https://ajax.googleapis.com/ajax/services/search/images?' + 'v=1.0&q='+searchTerm+'&start='+str(i*4)+'&userip=MyIP')
print (url)
request = urllib2.Request(url, None, {'Referer': 'testing'})
response = urllib2.urlopen(request)
# Get results using JSON
results = simplejson.load(response)
data = results['responseData']
dataInfo = data['results']
# Iterate for each result and get unescaped url
for myUrl in dataInfo:
count = count + 1
print (myUrl['unescapedUrl'])
myopener.retrieve(myUrl['unescapedUrl'],str(count)+'.jpg')
# Sleep for one second to prevent IP blocking from Google
time.sleep(1)
答案 0 :(得分:0)
如错误消息所述,FancyURLopener
不在您要查找的位置。这是正确的导入语句:
from urllib.request import FancyURLopener