一、error
1.URLError产生的原因:(1)没有网络;(2)服务器连接失败;(3)不知道指定服务器;(4)是OSError的子类
from urllib import request,error
if __name__ == "__main__":
url = "http://www.baidu.comfdsfdfsf"
try:
req = request.Request(url)
rsp = request.urlopen(req)
html = rsp.read().decode()
print(html)
except error.URLError as e:
print("URLError:{0}".format(e.reason))
print("URLError:{0}".format(e))
except Exception as e:
print(e)
2.HTTPError是URLError的一个子类
3.两者区别:HTTPError是对应的HTTP请求的返回码错误,如果返回错误码码是400以上的,则引发HTTPError;URLError对应的一般时网络出现问题,包括url问题;关系区别:OSError-URLError-HTTPError
二、useragent
1.UserAgent:用户代理,简称UA,属于heads的一部分,服务器通过UA来判断访问者身份;常见的UA值,使用的时候可以直接复制粘贴,也可以用浏览器访问的时候抓包。如下面的链接:
https://blog.csdn.net/wangqing84411433/article/details/89600335
2.设置UA可以通过两种方式:heads\
url2 = "http://www.baiu.com"
try:
#使用head方法伪装UA
headers = {}
headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
req2 = request.Request(url2,headers=headers)
rsp2 = request.urlopen(req2)
html2 = rsp2.read().decode()
print(html2)
except error.HTTPError as e:
print("URLError:{0}".format(e.reason))
print("URLError:{0}".format(e))
except error.URLError as e:
print("URLError:{0}".format(e.reason))
print("URLError:{0}".format(e))
except Exception as e:
print(e)
也可以把
req2 = request.Request(url2,headers=headers)
改成如下形式也可以
req2 = request.Request(url2)
req2.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko")
三、源码
Reptile4_ErrrorAndUserAgent.py
https://github.com/ruigege66/PythonReptile/blob/master/Reptile4_ErrrorAndUserAgent.py
2.CSDN:https://blog.csdn.net/weixin_44630050
3.博客园:https://www.cnblogs.com/ruigege0000/
4.欢迎关注微信公众号:傅里叶变换,个人公众号,仅用于学习交流,后台回复”礼包“,获取大数据学习资料