python|python urllib.request模块的使用详解
目录
- urllib子模块
- request模块
- function request.urlopen()
- class request.Request
urllib子模块
- urllib.request 打开或请求url
- urllib.error 捕获处理请求时产生的异常
- urllib.parse 解析url
- urllib.robotparser 用于解析robots.txt文件
request模块
function request.urlopen()
urlopen方法用来打开资源url,常用带参数形式urlopen(url,data=https://www.it610.com/article/None),url:资源url,data:携带的数据。
方法的返回值始终为一个对象,并可以调用相应的方法获取返回的信息。其中对于http及https的url来说会返回一个http.client.HTTPResponse对象;
import urllib.request# 我们用本地的一个简单html文件来测试url = 'http://127.0.0.1:8848/chenjy/test.html'req = urllib.request.urlopen(url)print(req)
文章图片
1. read() 返回服务器返回的原始数据;
import urllib.requesturl ='http://127.0.0.1:8848/chenjy/test.html'req = urllib.request.urlopen(url)print(req.read())
文章图片
我们可以再调用decode()方法来解码。
import urllib.requesturl = 'http://127.0.0.1:8848/chenjy/test.html'req = urllib.request.urlopen(url)print(req.read().decode())
文章图片
2.geturl() 返回获取资源的url;
- 创建一个测试页
import urllib.requesturl = 'http://127.0.0.1:8848/chenjy/test.html' req = urllib.request.urlopen(url)print(req.geturl())
文章图片
- 前端重定向
文章图片
- 后端重定向
@Overridepublic void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {int index = target.lastIndexOf("index.html"); if (index != -1){HandlerKit.redirect("/ls/html/list.html",request,response,isHandled); }}
import urllib.requesturl = 'http://localhost:8088/ls/index.html'req = urllib.request.urlopen(url)print(req.geturl())
文章图片
3.info() 返回页面的元信息;
import urllib.requesturl = 'http://127.0.0.1:8848/chenjy/test.html'req = urllib.request.urlopen(url)print(req.info())
文章图片
4.getcode() 返回页面的状态码;
import urllib.requesturl = 'http://127.0.0.1:8848/chenjy/test.html'req = urllib.request.urlopen(url)print(req.getcode())
文章图片
class request.Request
url请求类 Request(url, data=https://www.it610.com/article/None, headers={}, origin_req_host=None, unverifiable=False, method=None)
- url:请求url
- data:请求传参;bytes字节流
- headers:请求头
- origin_req_host:请求原始主机;不带端口
- unverifiable:是否不可验证;
- method :请求方法;如GET、POST、PUT等
import urllib.request# 模拟iphone5请求百度手机版页面url = 'https://www.baidu.com/'user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1'headers = {'User-Agent': user_agent}# 抓取page信息req = urllib.request.Request(url, headers=headers,method='GET')page = urllib.request.urlopen(req).read().decode('utf-8')print(page)
文章图片
【python|python urllib.request模块的使用详解】以上就是python urllib.request模块的使用详解的详细内容,更多关于python urllib.request模块的资料请关注脚本之家其它相关文章!
推荐阅读
- python学习之|python学习之 实现QQ自动发送消息
- 逻辑回归的理解与python示例
- SpringBoot调用公共模块的自定义注解失效的解决
- Node.js中readline模块实现终端输入
- python自定义封装带颜色的logging模块
- 解决SpringBoot引用别的模块无法注入的问题
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- Python基础|Python基础 - 练习1
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- Python(pathlib模块)