天天看点

python中urllib.request使用

requests比urllib.request更加强大便捷,但是urllib.request也有其优点。

我们都知道,urlopen()方法能发起最基本对的请求发起,但仅仅这些在我们的实际应用中一般都是不够的,可能我们需要加入headers之类的参数,那需要用功能更为强大的Request类来构建了

GET请求

可直接通过urlopen()方法来发起一个简单的web请求。如下请求https的网站并携带headers信息

import urllib.request
import ssl
#添加Headers信息
headers = {
     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36',
 }
url = 'https://www.baidu.com/'
#防止ssl报错
context = ssl._create_unverified_context()

re = urllib.request.Request(url=url,headers=headers)
response = urllib.request.urlopen(re,context=context)
print(response.read().decode('utf-8'))#urlopen()方法返回的是一个http.client.HTTPResponse对象,需要通过read()方法做进一步的处理。一般使用read()后,我们需要用decode()进行解码,通常为utf-8
           
python中urllib.request使用