URLError的使用

URLError可能产生的原因
1.网络无连接,即本机无法上网
2.连接不到待定的服务器
3.服务器不存在

通过try-except完成

from urllib.request import Request,urlopen
from urllib.error import URLError

url = "http://www.zu66698.e8787u.cn/"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36 Edg/83.0.478.54"
}
try:
    request = Request(url,headers=headers)
    response = urlopen(request)
    print(response.read().decode())
except URLError as e:
    if e.args == ():
        print(e)
    else:
        print(e.args[0].error)


    #print(e)

print("访问完成")

你可能感兴趣的:(Python爬虫)