首页 > 解决方案 > 未找到 Urllib2 模块

问题描述

我在网上找到了这个下载漫画的python脚本。当我尝试运行它时,出现错误:“Traceback(最近一次调用最后一次):文件“/Users/Jake/Desktop/garfield-downloader-master/garfield.py”,第 10 行,在 import urllib2 ModuleNotFoundError:没有模块名为'urllib2'”的代码如下。

from datetime import date,timedelta
import urllib2
import os

def daterange(start,end):
    for x in range(int ((end - start).days)):
        yield start + timedelta(x)

#Create the Directory, if not already existing
dir = "./garfield/"
if not os.path.exists(dir):
    os.makedirs(dir)
    
start_date = date.today()
    
#Garfield Started on 19th June, 1978
start_date = start_date.replace(year=1978,month=6,day=19)
end_date = date.today()

for single_day in daterange(start_date,end_date):
    link = "https://d1ejxu6vysztl5.cloudfront.net/comics/garfield/" + (str(single_day)[:4]) + "/" + str(single_day) + ".gif"
    print(single_day)

    #checks whether the files already exist or not  
    filename = dir+str(single_day)+".gif"
    if not os.path.exists(filename): 
        try:
            f = urllib2.urlopen(link)
        except urllib2.URLError:
            if e.code == 404:
                continue
        print ("Downloading :: " + link)
    
        save_file = open(dir+str(single_day)+".gif","w"+'b')
        save_file.write(f.read())
        save_file.close()

print("Garfield Comics has been downloaded")

标签: python

解决方案


正如文档所述,urllib2在 Python 3 中已拆分为多个模块,即urllib.request实现urllib.error您正在调用的相同方法。例如,

from urllib.request import urlopen

推荐阅读