python之urllib.request模块 作者:马育民 • 2019-01-14 12:45 • 阅读:10145 # urllib.request模块 定义若干函数和类,用于访问url,底层调用的 **http.client模块** ,但是提供了更加强大的功能,更简便的操作方式 官方网址: https://docs.python.org/3/library/urllib.request.html?highlight=urllib#module-urllib.request ## urlopen函数 向web服务器发请求,打开url连接 ### 语法 ``` urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None) ``` **参数:** - url:网址 - data:data为None时,GET请求;不为None时,POST方法提交数据 - timeout:设置网站的访问超时时间 **返回:** 返回http.client.HTTPResponse对象 ###例子 发送GET请求 ``` from urllib import request with request.urlopen('http://www.sohu.com/') as resp: print(resp.status, resp.reason,resp.version) print(resp.headers) if resp.status==200: data = resp.read() contenttype=resp.getheader('Content-Type') charset=contenttype.split('charset=')[1] print( data.decode(charset)) ``` ## Request类 通过该类封装请求头信息,再通过urlopen()向服务器发请求 ### 语法: ``` urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None) ``` **参数:** - url:网址 - data:提交的数据 - headers:请求头 **返回:** Request对象 ###例子 ``` from urllib import request url = r'http://www.lagou.com/zhaopin/Python/?labelWords=label' headers = { 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3', 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label', 'Connection': 'keep-alive' } req=request.Request(url, headers=headers) with request.urlopen(req) as resp: print(resp.status, resp.reason,resp.version) print(resp.headers) if resp.status==200: data = resp.read() contenttype=resp.getheader('Content-Type') charset=contenttype.split('charset=')[1] print( data.decode(charset)) ``` ## urlencode 将post要提交的数据进行编码 ### 语法 ``` urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None) ``` **参数:** - query: 要编码的数据 **返回值:** 返回编码后的数据 ### 例子 通过post方法提交数据 ``` from urllib import request, parse url = r'http://www.lagou.com/jobs/positionAjax.json?' headers = { 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3', 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label', 'Connection': 'keep-alive' } data = { 'first': 'true', 'pn': 1, 'kd': 'Python' } data = parse.urlencode(data).encode('utf-8') print(data) req = request.Request(url, headers=headers, data=data) page = request.urlopen(req).read() page = page.decode('utf-8') ``` 感谢: https://www.cnblogs.com/Lands-ljk/p/5447127.html 原文出处:http://www.malaoshi.top/show_1EF2bq7Z3osN.html