<urlopen error [Errno 11001] getaddrinfo failed>的解决、isinstance()函数初略介绍

1,错误分析

爬虫实践时遇到了<urlopen error [Errno 11001] getaddrinfo failed>这个问题!

与我实践所要求的结果不一样(<urlopen error timed out>我想得到的是这个网络超时)

百度了一下发现与我的情况都不一样。

✅链接网址问题,链接不存在或者打错了

✅网址单双引号问题

还有我的这种情况,就是单纯的没联网,当然就无法访问(被自个逗到了)

import urllib.request
import urllib.error
url='https://www.python.org/'
try:
    #发送网络请求,设置时间为0.1秒
    response=urllib.request.urlopen(url=url,timeout=0.1)
    print(response.read().decode('utf-8'))
except urllib.error.URLError as error:
    print(error)

联网后结果是:

顺便扩展一下:python内置函数

isinstance()的用法:用来判断错误类型是否一样,返回值为True或False,
语法:isinstance(实例对象,类名、基本类型或其组合)

类型相同则返回true,否则返回false

import urllib.request                                      #导入urllib.request模块
import urllib.error                                        #导入urllib.error模块
import socket                                              #导入socket模块
url='https://www.python.org/'                              #请求地址                                      
try:
    #发送网络请求,设置时间为0.1秒
    response=urllib.request.urlopen(url=url,timeout=0.1)    
    print(response.read().decode('utf-8'))                 #读取HTML代码并utf—8解码   
except urllib.error.URLError as error:                     #处理异常
    print(error)                                           #输出错误
    if isinstance(error.reason,socket.timeout):            #判断是否为超时异常
        print('当前任务已超时,即将执行下一任务!')

来源:致奋斗的自己

物联沃分享整理
物联沃-IOTWORD物联网 » <urlopen error [Errno 11001] getaddrinfo failed>的解决、isinstance()函数初略介绍

发表评论