'''定義一個函數func(urllist) urllist:為URL的列表,例如:['http://xx.com','http://www.xx.com','http://www.xxx.com'...] 函數功能:要求依次打開url,打印url對應的內容,如果有的url打不開,則把url記錄到日志文件里,並且跳過繼續訪問下個url。'''
def func(urllist): for url in urllist: # 遍歷每一個網址 try: open_url = request.urlopen(url) # 打開網址 except IOError as e: now_time = datetime.datetime.now().strftime('%Y-%m-%d') # 獲取當前時間 log = now_time+'log.txt' # 定義日志文件名 with open(log, 'a', encoding="utf-8") as f: # with open()方法打開日志文件,如果沒有就新生成一個文件,a追加內容 f.write(url+',網站打開失敗,拋出異常:'+str(e)+'\n') # 將錯誤寫入日志文件 else: comment = open_url.read() # 讀取網頁內容 return comment # 返回網頁內容 print(func(['http://adfdsfsd', 'https://www.baidu.com/', 'https://www.liaoxuefeng.com/']))