一、Python urllib库
Python urllib 库用于操作网页 URL,并对网页的内容进行抓取处理。
Python3 的 urllib。
urllib 包 包含以下几个模块:
-
urllib.request - 打开和读取 URL。
-
urllib.error - 包含 urllib.request 抛出的异常。
-
urllib.parse - 解析 URL。
-
urllib.robotparser - 解析 robots.txt 文件。
需要用的就是每个模块的内置方法和函数。大概方法如下图:
二、urllib.request模块
urllib.request 定义了一些打开 URL 的函数和类,包含授权验证、重定向、浏览器 cookies等。
urllib.request 可以模拟浏览器的一个请求发起过程。
这里主要介绍两个常用方法,urlopen和Request。
1. urlopen函数
语法格式如下:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
-
url:url 地址。
-
data:发送到服务器的其他数据对象,默认为 None。
-
timeout:设置访问超时时间。
-
cafile 和 capath:cafile 为 CA 证书, capath 为 CA 证书的路径,使用 HTTPS 需要用到。
-
cadefault:已经被弃用。
-
context:ssl.SSLContext类型,用来指定 SSL 设置。
示例:
import urllib.request
#导入urllib.request模块
url=urllib.request.urlopen("https://www.baidu.com")
#打开读取baidu信息
print(url.read().decode('utf-8'))
#read获取所有信息,并decode()命令将网页的信息进行解码
运行结果:
<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always" name="
html{color:#000;overflow-y:scroll;overflow:-moz-scrollbars}
body,button,input,select,textarea{font-size:12px;font-family:Arial,sans-serif}
h1,h2,h3,h4,h5,h6{font-size:100%}
em{font-style:normal}
small{font-size:12px}
ol,ul{list-style:none}
a{text-decoration:none}
a:hover{text-decoration:underline}
legend{color:#000}
fieldset,img{border:0}
button,input,select,textarea{font-size:100%}
...
response对象是http.client. HTTPResponse类型,主要包含 read、readinto、getheader、getheaders、fileno 等方法,以及 msg、version、status、reason、debuglevel、closed 等属性。
常用方法:
- <