urllib.request.urlopen(url, data=None, timeout=n) 用于发送HTTP请求并得到响应内容
In [1]: import urllib.requestIn [2]: response = urllib.request.urlopen("http://www.baidu.com/") ???//发送GET请求In [3]: response.read().decode(‘utf-8‘) ???//read()方法用于获取响应内容,readline(),readlines()也可以In [4]: response.status ???????????????????//status属性用于获取响应状态码In [5]: response.getcode() ????????????????//getcode()方法用于获取响应状态码In [6]: response.geturl() ?????????????????//geturl()方法用于获取请求的源地址In [7]: response.getheaders() ?????????????//getheaders()方法用于获取响应头信息In [8]: response.getheader(‘Server‘) ??????//getheader()方法用于获取指定的响应头信息
data 参数:
(1) 该参数是可选的,如果要添加,则必须通过 urllib.parse.urlencode() 转换成字节流编码格式
(2) 另外,如果传递了这个参数,则它的请求方式就不再是 GET 方式,而是 POST 方式,以下两种方式是一样的
import urllib.requestresponse = urllib.request.urlopen("http://www.baidu.com/s?wd=hello")
import urllib.parseimport urllib.requestdata = bytes(urllib.parse.urlencode({‘wd‘: ‘hello‘}), encoding=‘utf-8‘)respose = urllib.request.urlopen("http://www.baidu.com/", data=data)
timeout 参数:
有时候我们访问一个网页,如果该网页长时间未响应,那么系统就会判断该网页超时了,即无法打开该网页,因此我们在打开一个URL时要根据自己的需要来设置超时时间
import urllib.requesttry: ????????data = urllib.request.urlopen("http://www.baidu.com/", timeout=3).read()except Exception as e: ???print("请求超时!")
使用 urllib 发送请求
原文地址:https://www.cnblogs.com/pzk7788/p/10531002.html