python3中使用urllib进行https请求

刚入门python学习网络爬虫基础,我使用的python版本是python3.6.4,学习的教程参考Python爬虫入门教程

python3.6的版本已经没有urllib2这个库了,所以我也不需要纠结urllib和urllib2的区别和应用场景

>>> import urllib2
Traceback (most recent call last): 
 File "", line 1, in 
    import urllib2
ModuleNotFoundError: No module named 'urllib2'

参考这篇官方文档 HOWTO Fetch Internet Resources Using The urllib Package 。关于http(s)请求一般就get和post两种方式较为常用,所以写了以下两个小demo,url链接随便找的,具体场景具体变化,可参考注释中的基本思路

POST请求:

#post请求提交用户信息到服务器

import urllib.request
import urllib.parse
import ssl

context = ssl._create_unverified_context()

#CGI(Common Gateway Interface)是HTTP服务器运行的程序
#通过Internet把用户请求送到服务器
#服务器接收用户请求并交给CGI程序处理
#CGI程序把处理结果传送给服务器
#服务器把结果送回到用户

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {
'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python' }
data = urllib.parse.urlencode(values).encode('ascii')

req = urllib.request.Request(url, data=data)

with  urllib.request.urlopen(req, context=context) as response:
html = response.read()
print(html)

GET请求:

#get请求提交用户信息到服务器

import urllib.request
import urllib.parse
import ssl

data = {}

data['name'] = 'Somebaby Here'
data['location'] = 'Northampton'
data['language'] = 'Python'

url_para = urllib.parse.urlencode(data)
url = 'http://www.example.com/example.cgi'
full_url = url + '?' + url_para

context = ssl._create_unverified_context()

with urllib.request.urlopen(full_url, context=context) as response:
html = response.read()
print(response.code())#200是正常响应

注意,
使用ssl创建未经验证的上下文,在urlopen中需传入上下文参数
urllib.request.urlopen(full_url, context=context)
这是Python 升级到 2.7.9 之后引入的一个新特性,所以在使用urlopen打开https链接会遇到如下报错:
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)
所以,当使用urllib.urlopen打开一个 https 链接时,需要先验证一次 SSL 证书
context = ssl._create_unverified_context()
或者或者导入ssl时关闭证书验证
ssl._create_default_https_context =ssl._create_unverified_context

你可能感兴趣的:(python3中使用urllib进行https请求)