使用 urllib 发送请求

urllib.request.urlopen(url, data=None, timeout=n) 用于发送HTTP请求并得到响应内容

In [1]: import urllib.request
In [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.request
response = urllib.request.urlopen("http://www.baidu.com/s?wd=hello")
import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'wd': 'hello'}), encoding='utf-8')
respose = urllib.request.urlopen("http://www.baidu.com/", data=data)


timeout 参数:

有时候我们访问一个网页,如果该网页长时间未响应,那么系统就会判断该网页超时了,即无法打开该网页,因此我们在打开一个URL时要根据自己的需要来设置超时时间

import urllib.request

try:     
    data = urllib.request.urlopen("http://www.baidu.com/", timeout=3).read()
except Exception as e:
    print("请求超时!")

 

 

 

 

 

 

     

posted @ 2019-03-14 16:13  孔雀东南飞  阅读(369)  评论(0编辑  收藏  举报