这是我参与2022首次更文挑战的第14天,活动详情查看:2022首次更文挑战」
今天是腊月29 ,今年可没有年三十啊,未来几年也没有年三十,祝大家春节快乐.
上一篇文章,解决了怎么获得cookie的问题,今天的文章来解决,怎么使用这个cookie
书上是以LWPCookieJar来作为例子 代码与书上相比多了ssl的东西,因为我使用的Python3.10版本,可能对于ssl证书要求的比较严格
import urllib.request,http.cookiejar
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
cookie = http.cookiejar.LWPCookieJar()
cookie.load("cookie.txt",ignore_expires=True,ignore_discard=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
reponse = opener.open("https://www.baidu.com")
print(reponse.read().decode("utf-8"))
得到的结果:
<html>
<head>
<script>
location.replace(location.href.replace("https://","http://"));
</script>
</head>
<body>
<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>
处理异常
我现在已经学会了如何发送请求,但是如果网不好,或者代理没设对,或者ssl证书的问题,就会出现异常,出现异常,我们就要处理异常.
URLError
URLError 有一个reason属性,这是反回错误的原因: 举个例子:
from urllib import request,error
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
try:
response = request.urlopen("https://cuiqingcai.com/404")
except error.URLError as e:
print(e)
返回结果: HTTP Error 404: Not Found 前面说过了,可以有一个reason属性,可以看到原因,那么它的响应是: Not Found 这里访问的书上崔老师的例子,应该是一个404的错误页面
我觉得异常处理好处不仅仅在于,程序出现错误了,还可以继续执行,我感觉更在于你对于你写的代码的理解,你知道你可能会遇到的问题,提前想好问题,代表了你的思考.
HTTPError
HTTPError 是URLError的子类,专门用来处理HTTP请求的,主要有三个属性:
- code 状态码 404 200 500 这些
- reason 更上面一样,返回错误的原因
- headers 返回请求头
举个例子:
import ssl
from urllib import request,error
ssl._create_default_https_context = ssl._create_unverified_context
try:
response = request.urlopen("https://cuiqingcai.com/404")
except error.HTTPError as e:
print(e.reason,e.code,e.headers)
返回结果:
Not Found 404 Server: GitHub.com
Content-Type: text/html; charset=utf-8
Access-Control-Allow-Origin: *
ETag: "5ececa4d-247b"
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'
x-proxy-cache: MISS
X-GitHub-Request-Id: 1C8A:668D:149DDE1:16B2712:61F70B46
Accept-Ranges: bytes
Date: Sun, 30 Jan 2022 22:21:09 GMT
Via: 1.1 varnish
Age: 1038
X-Served-By: cache-hkg17928-HKG
X-Cache: HIT
X-Cache-Hits: 1
X-Timer: S1643581269.389181,VS0,VE0
Vary: Accept-Encoding
X-Fastly-Request-ID: ef2ae6076f785381b7aba99d91fbe150ccde22a5
X-Cache-Lookup: Cache Miss
X-Cache-Lookup: Cache Miss
X-Cache-Lookup: Cache Miss
Content-Length: 9339
X-NWS-LOG-UUID: 3612849711459983710
Connection: close
X-Cache-Lookup: Cache Miss
崔老师的书上给出了一个更好地写法,先捕获子类的错误,再捕获父类的错误,更好地写法:
import ssl
from urllib import request,error
ssl._create_default_https_context = ssl._create_unverified_context
try:
response = request.urlopen("https://cuiqingcai.com/404")
except error.HTTPError as e:
print(e.reason,e.code,e.headers)
except error.URLError as e:
print(e.reason)
else:
print("Successfully")
不得不说,崔老师这本书真厚啊,太全了,我不知道我什么时候才能给他翻一遍,新年快乐,铁子们