1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import urllib.request import http.cookiejar import ssl # 取消全局SSL验证,不写这句 可能会报SSL验证失败 ssl._create_default_https_context = ssl._create_unverified_context baiduCookieFileName = "cookie.txt" # 获取百度cookies baidu_cookie = http.cookiejar.MozillaCookieJar(baiduCookieFileName) proHandler = urllib.request.HTTPCookieProcessor(baidu_cookie) opener = urllib.request.build_opener(proHandler) # 注意这里是 https 不是http,我一开始写成http,一直报 urllib.error.HTTPError: HTTP Error 400: Bad Request baidu_url = 'http://www.baidu.com' # 访问百度 response = opener.open(baidu_url) # 打印cookies for item in baidu_cookie: print("name = " + item.name) print("value = " + item.value) # 保存cookie到文件 baidu_cookie.save(ignore_discard=True, ignore_expires=True) |
遇到urllib.error.HTTPError: HTTP Error 400: Bad Request,400: Bad Request这个错误,查了半天,最终发现是url错了。目标网站使用的是https协议,而我写的时候写成了http,则运行出现如下错误:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
D:\python\python.exe E:/技术学习/Python代码/10.保存cookies到文件/savecookieinflie.py Traceback (most recent call last): File "E:/技术学习/Python代码/10.保存cookies到文件/savecookieinflie.py", line 15, in <module> response = opener.open(baidu_url) File "D:\python\lib\urllib\request.py", line 532, in open response = meth(req, response) File "D:\python\lib\urllib\request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "D:\python\lib\urllib\request.py", line 570, in error return self._call_chain(*args) File "D:\python\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "D:\python\lib\urllib\request.py", line 650, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 400: Bad Request 进程已结束,退出代码1 |
解决方案,把链接的http协议改成https就解决了:
1 2 |
# 注意这里是 https 不是http,我一开始写成http,一直报 urllib.error.HTTPError: HTTP Error 400: Bad Request baidu_url = 'https://www.baidu.com' |
转载请注明:燕骏博客 » Python3.6问题总结之一:urllib.error.HTTPError: HTTP Error 400: Bad Request
赞赏作者微信赞赏支付宝赞赏