今天就跟大家聊聊有关如何在python项目中使用urllib。请求模块,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
urllib子模块
- <李>
urllib。url请求打开或请求
李> <李>urllib。错误捕获处理请求时产生的异常
李> <李>urllib。url解析解析
李> <李>urllib。robotparser用于解析robots . txt文件
李>机器人。txt是一种存放于网站根目录下文本文件,用来告诉网络爬虫服务器上的那些文件可以被查看。又被成为机器人协议,是一种约定俗成的协议。
请求模块
函数request.urlopen ()
urlopen方法用来打开资源url,常用带参数形式urlopen (url, data=https://www.yisu.com/zixun/None), url:资源url,数据:携带的数据。
方法的返回值始终为一个对象,并可以调用相应的方法获取返回的信息。其中对于http及https的url来说会返回一个http.client.HTTPResponse对象,
import urllib.request #,我们用本地的一个简单html文件来测试 时间=url & # 39; http://127.0.0.1:8848 chenjy test.html& # 39; 时间=req urllib.request.urlopen (url) 打印(点播)
1。read()返回服务器返回的原始数据;
import urllib.request url =& # 39; http://127.0.0.1:8848 chenjy test.html& # 39; 时间=req urllib.request.urlopen (url) print (req.read ())
我们可以再调用解码()方法来解码。
import urllib.request 时间=url & # 39; http://127.0.0.1:8848 chenjy test.html& # 39; 时间=req urllib.request.urlopen (url) 打印(req.read () .decode ())
2. geturl()返回获取资源的url;
- <李>
创建一个测试页
import urllib.request 时间=url & # 39; http://127.0.0.1:8848 chenjy test.html& # 39;, 时间=req urllib.request.urlopen (url) print (req.geturl ())
- <李>
前端重定向
我们在页面中添加js脚本重定向页面window.location.href=https://www.yisu.com/zixun/http://127.0.0.1:8848 chenjy test2.html的;,会发现访问的时候会重定向到test2,但是geturl还是获取的重定向前的
- <李>
后端重定向
我们启动一个项目并添加一个拦截器当访问index . html的时候重定向到/ls/html/列表。html页面,geturl获取的是重定向后的页面
@Override ,,,,,public void 处理(String 目标,HttpServletRequest 请求,,HttpServletResponse 反应,,布尔[],isHandled), { ,,,,,,,int index =, target.lastIndexOf (“index.html"); ,,,,if 才能;(index !=, 1) { ,,,,,,,,HandlerKit.redirect (“/ls/html/list.html",请求,响应,isHandled); ,,,,,,} ,,,,,,, ,,,,,}
import urllib.request 时间=url & # 39; http://localhost: 8088/ls/index . html # 39; 时间=req urllib.request.urlopen (url) print (req.geturl ())
3. info()返回页面的元信息;
import urllib.request 时间=url & # 39; http://127.0.0.1:8848 chenjy test.html& # 39; 时间=req urllib.request.urlopen (url) print (req.info ())