'''定义一个函数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/']))

 

相关文章:

  • 2022-03-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-01
  • 2021-08-30
  • 2021-12-12
  • 2022-12-23
猜你喜欢
  • 2021-11-13
  • 2021-05-25
  • 2021-04-05
  • 2022-01-23
  • 2021-06-08
  • 2021-10-21
  • 2021-08-29
相关资源
相似解决方案