urllib库是Python3的一个内置标准库,主要用来进行http请求。
request模块功能提供一个基本的请求功能,来模拟http请求。
目前更常用的是第三方库:request,是基于urlib库封装的。
下面是urlib库的常用方法:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time:2021/3/29 10:31
# @Author:九九的金金子
import urllib.request
# 打开地址:http://wwww.baidu.com
response = urllib.request.urlopen("http://wwww.baidu.com")
print("\nstatus:", response.status) # 请求状态
print("\nheaders:", response.headers) # 请求头
# print("\nread:", response.read().decode('utf-8')) # 请求返回的内容
运行结果:
status: 200
headers: Connection: close
Transfer-Encoding: chunked
Bdpagetype: 1
Bdqid: 0xaaf1c78200030001
Cache-Control: private
Content-Type: text/html;charset=utf-8
Date: Mon, 29 Mar 2021 04:23:04 GMT
Expires: Mon, 29 Mar 2021 04:22:38 GMT
P3p: CP=" OTI DSP COR IVA OUR IND COM "
P3p: CP=" OTI DSP COR IVA OUR IND COM "
Server: BWS/1.1
Set-Cookie: BAIDUID=23344C6BD396723215C031BC3D887B8C:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BIDUPSID=23344C6BD396723215C031BC3D887B8C; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: PSTM=1616991784; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BAIDUID=23344C6BD3967232404175022D60765D:FG=1; max-age=31536000; expires=Tue, 29-Mar-22 04:23:04 GMT; domain=.baidu.com; path=/; version=1; comment=bd
Set-Cookie: BDSVRTM=0; path=/
Set-Cookie: BD_HOME=1; path=/
Set-Cookie: H_PS_PSSID=33739_33273_31254_33392_33714_26350_22159; path=/; domain=.baidu.com
Traceid: 1616991784023877684212317845816994889729
Vary: Accept-Encoding
Vary: Accept-Encoding
X-Ua-Compatible: IE=Edge,chrome=1