Python requests库
requests是一个用于在程序中进行http协议下的get和post请求的库。
安装
easy_install requests
或者用
pip install requests
安装好之后在交互模式下运行
>>> import requests >>> dir(requests) ['ConnectionError', 'HTTPError', 'NullHandler', 'PreparedRequest', 'Request', 'RequestException', 'Response', 'Session', 'Timeout', 'TooManyRedirects', 'URLRequired', '__author__', '__build__', '__builtins__', '__copyright__', '__doc__', '__file__', '__license__', '__name__', '__package__', '__path__', '__title__', '__version__', 'adapters', 'api', 'auth', 'certs', 'codes', 'compat', 'cookies', 'delete', 'exceptions', 'get', 'head', 'hooks', 'logging', 'models', 'options', 'packages', 'patch', 'post', 'put', 'request', 'session', 'sessions', 'status_codes', 'structures', 'utils']
从上面的列表中可以看出在http中常用到的getcookiespost等都赫然在目。
get请求
>>> r = requests.get("http://www.hiekay.com")
得到一个请求的实例然后
>>> r.cookies <RequestsCookieJar[]>
这个网站对客户端没有写任何cookies内容。换一个看看
>>> r = requests.get("http://www.baidu.com") >>> r.cookies <<class 'requests.cookies.RequestsCookieJar'>[Cookie(version=0, name='PHPSESSID', value='buqj70k7f9rrg51emsvatveda2', port=None, port_specified=False, domain='www.baidu.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]>
原来这样呀。继续还有别的属性可以看看。
>>> r.headers {'Content-Encoding': 'gzip', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Server': 'bfe/1.0.8.18', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:24 GMT', 'Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Date': 'Wed, 16 Jan 2019 07:42:13 GMT', 'Content-Type': 'text/html'} >>> r.encoding 'UTF-8' >>> r.status_code 200
下面这个比较长是网页的内容仅仅截取显示部分
>>> print r.text <!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><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç¾åº¦ä¸ä¸ï¼ä½ å°±ç¥é</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç¾åº¦ä¸ä¸ class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ°é»</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å°å¾</a> ......
请求发出后requests会基于http头部对相应的编码做出有根据的推测当你访问r.text之时requests会使用其推测的文本编码。你可以找出requests使用了什么编码并且能够使用r.coding属性来改变它。
>>> r.content '<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> ...... 以二进制的方式打开服务器并返回数据。
post请求
requests发送post请求通常你会想要发送一些编码为表单的数据——非常像一个html表单。要实现这个只需要简单地传递一个字典给data参数。你的数据字典在发出请求时会自动编码为表单形式。
>>> import requests >>> payload = {"key1":"value1","key2":"value2"} >>> r = requests.post("http://httpbin.org/post") >>> r1 = requests.post("http://httpbin.org/post", data=payload)
看看效果
http头部
>>> r.headers['content-type'] 'application/json'
注意在引号里面的内容不区分大小写'CONTENT-TYPE'
也可以。
还能够自定义头部
>>> r.headers['content-type'] = 'adad' >>> r.headers['content-type'] 'adad'
注意当定制头部的时候如果需要定制的项目有很多需要用到数据类型为字典。
-
- *
备注
网上有一个更为详细叙述有关requests模块的网页可以参考http://requests-docs-cn.readthedocs.org/zh_CN/latest/index.html
低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
java B2B2C 源码 springmvc mybatis多租户电子商城系统- Stream重新入队(RabbitMQ)
本文将介绍RabbitMQ的binder提供的重试功能:重新入队 准备一个会消费失败的例子,可以直接沿用前文的工程,也可以新建一个,然后创建如下代码的逻辑: @EnableBinding(TestApplication.TestTopic.class) @SpringBootApplication public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } @RestController static class TestController { @Autowired private TestTopic testTopic; /** * 消息生产接口 * * @param message * @return */ @GetMapping("/sendMessage") public String messageWithMQ(@RequestParam String message) { testT...
- 下一篇
JAVA学习day08
1、快捷键 Alt+/ 自动补全 写程序的时候,之写出一部分 输出 syso 类名 Scanner 起名字 如Int 按下alt+/会帮你带出变量 Ctrl+Shift+F 代码格式化 Ctrl+/ 单行注释 取消单行注释就再按一次 Ctrl+Shift+/ 多行注释 Ctrl+Shift+\ 取消多行注释 Ctrl+Shift+o 导入包的快捷键 Alt+上下箭头 移动当前行代码 Ctrl+alt+上下箭头 复制当前代码行 Ctrl+D 删除当前行 Ctrl+1 意见提示功能 2、调试代码 • 断点: 就是一个标记 • 如何设置断点 ○ 代码区域左边的空白位置 双击即可 • 在哪里加 ○ 想看哪个语句的执行结果就在该语句前面加 • 怎么运行断点的程序 ○ 代码区域右键 -- Debug as -- Java Application ○ 显示一个页面,提示是否进入调试页面? 是否记住当前操作?是(Yes)是(勾选复选框) • 弹出了断点页面 ○ 点哪里 § 点击 工具栏中的Step Over (执行下一行) § 快捷键F6 看到每一步程序的执行过程 ○ 看哪里 § 看代码区域: 对照看...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- CentOS8编译安装MySQL8.0.19
- CentOS8,CentOS7,CentOS6编译安装Redis5.0.7
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- SpringBoot2整合Redis,开启缓存,提高访问速度
- SpringBoot2配置默认Tomcat设置,开启更多高级功能
- Hadoop3单机部署,实现最简伪集群
- CentOS7,CentOS8安装Elasticsearch6.8.6
- CentOS6,7,8上安装Nginx,支持https2.0的开启
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果