1.urlib库是python内置的http请求库,它可以看作处理url的组件集合。urllib库包含4大模块:
(1)urllib.request:请求模块
(2)urllib.error: 异常处理模块
(3)urllib.parse:URL解析模块
(4)urllib.robotparser:robots.txt解析模块
下面是用urllib库爬取百度首页
import urllib.request # 导入urllib的请求模块request
url = "http://www.baidu.com"
response = urllib.request.urlopen(url) # 调用urllib.request库的urlopen()方法打开网址
html = response.read().decode("utf-8") # 使用read()方法读取爬到的内容,并以utf-8方式编码
print(response.status) # 打印响应的状态码
print(html)
以上代码打印出来就可以看到我们把百度首页的网页源码全部爬下来了
2.分析urlopen()方法
urlopen()可以接受多个参数,该方法的定义如下:
urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None,capath=None,cadefault=False,context=None)
上述方法的定义中的详细参数介绍如下:
(1)url:url地址的字符串,也可以是一个urllib.request对象
(2)data:必须是一个bytes对象;data必须符合它的标准格式,使用urllib.parse.urlencode()可以将自定义的data转换为标准格式,当用设置了data参数时,需要将请求改为post请求;当没有设置时以get方式请求。
(3)timeout:该参数用于设置超时时间,单位为秒。
(4)cafile/capath/cadefault:用于实现可信任的CA证书的HTTPS请求
(5)context:用于实现SSL加密传输
data参数的使用实例:
import urllib.request
import urllib.parse
url = "http://httpbin.org/post" # 这个网站可以测试post请求
data = {"word": "hello"}
datas = bytes(urllib.parse.urlencode(data).encode("utf-8"))
response = urllib.request.urlopen(url, data=datas)
print(response.read())
打印结果如下:
"{
"args": {},
"data": "",
"files": {},
"form": {
"word": "hello"
},
"headers": {
"Accept-Encoding": "identity",
"Content-Length": "10",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Python-urllib/3.6",
"X-Amzn-Trace-Id": "Root=1-61a0d4a8-7d86e6c70769eacc767cc4ce"
},
"json": null,
"origin": "111.2.154.24",
"url": "http://httpbin.org/post"
}
"timeout参数的使用示例:
import urllib.request
url = "http://httpbin.org/get"
response = urllib.request.urlopen(url, timeout=0.1)
print(response.read())
运行结果报错:During handling of the above exception, another exception occurred:
urllib.error.URLError: <urlopen error timed out>
这里我们设置超时时间是0.1秒,程序0.1秒过后,服务器没有响应,于是报错了,错误原因是请求超时。
版权声明:本文为w_sunset原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。