天天看点

urllib的用法urllib.request模块的用法

urllib.request模块的用法

urlopen

urllib.request.urlopen(url),括号内可传递的参数除了url,还有timeout, cafile,capath,context。

下面详细介绍各参数

data:如果是字节流编码格式的内容,需要用bytes()方法进行转化,

当传递这个参数后,请求方式就不再是GET,而是POST。bytes(str,encoding=‘utf8’),bytes的第一个参数是字符串,如果是字典, 需要使用*urllib.parse.urlencode()*方法来将字典转化为字符串,第二个参数是编码格式。

timeout:设置超时时间,单位是s。

cafile:CA证书

capath:CA证书路径

context:必须是SSLContext类型,用来指定ssl设置。

代码如下:

import urllib.parse
import urllib.request

url = 'http://httpbin.org/post'
# 对参数data进行格式转化
data = bytes(urllib.parse.urlencode({'word':'hello'}), encoding='utf8')
# urlopen 可传递的参数除了url 还有timout等其他参数
response = urllib.request.urlopen(url, data=data, timeout=100,capath=None,cafile=None,context=None,cadefault=False)
print(response.read())
           

Request的用法

urlopen()方法可以实现最基本请求的发起,如果请求中需要加入Header等信息可以利用强大的Request类来构建。

Request的参数:url,data,header,origin_req_host, unverifable, method.

oringin_req_host: 请求方的host名称或IP

univerfable: 表示这个请求是不是无法验证的。默认为False,即有足够的请求权限。

method: 是一个字符串,表示请求方法,即GET,POST,PUT.

代码如下:

import urllib.request
import urllib.parse

url = 'http://httpbin.org/post'
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
    'host': 'httpbin.org',
}
dict={
    'name':'Germey'
}

data = bytes(urllib.parse.urlencode(dict),encoding='utf8')
equest = urllib.request.Request(url,data=data, headers=headers, method='POST')
# 发起请求并获取请求结果
res = urllib.request.urlopen(request)
print(res.read().decode('utf-8'))
           

以上就是本篇文章的所有内容