前文提到过urllib2库,此处做简单的学习和总结。
urllib2是Python 2.7自带的库,无需下载,使用时导入即可,urllib2 官方文档:https://docs.python.org/2/library/urllib2.html
在Python 3.x中,为urllib,由于我使用的是Python 3.6,故后期实践中应用urllib
urllib官方文档:https://docs.python.org/3/library/urllib.html
1. urllib.request——请求模块
urllib.request.
urlopen
(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
看一个官网上的例子
import urllib.request
with urllib.request.urlopen('http://www.python.org') as f:
print(f.read(300))
# 运行结果
# b'<!doctype html>\n<!--[if lt IE 7]> <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9"> <![endif]-->\n<!--[if IE 7]> <html class="no-js ie7 lt-ie8 lt-ie9"> <![endif]-->\n<!--[if IE 8]> <html class="no-js ie8 lt-ie9"> <![endif]-->\n<!--[if gt IE 8]><!--><html class="no-js"'
如果将代码改为
import urllib.request
with urllib.request.urlopen('http://www.python.org') as f:
print(f)
# 运行结果
# <http.client.HTTPResponse object at 0x0BCA9C30>
f.read()可以获取网页的内容,print(f.read(300))将显示前300字节的网页内容
在上述的例子中,参数只有url,这种请求方式叫做get请求方式
再看另外一个例子
import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
print(data)
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())
这个例子中,将参数data以bytes形式传入,这种请求方式叫做POST请求(此处代码来源于https://www.cnblogs.com/zhaof/p/6910871.html),urllib.parse.urlencode()的具体作用可以参看:http://dev.fyicenter.com/1000973_Using_urllib_parse_urlencode_.html