Requests库从入门到放弃

Requests库从入门到放弃

一个很牛逼的http库,就这样子
1.get,post,cookie,header是什么还说么?直接上代码

2.安装requests库

pip install requests

3.get方法使用

import requests
r = requests.get('https://github.com/timeline.json')
print r.text

4.post方法使用
(1)普通post请求发送数据

import requests
#传递的数据用字典表示
payload = {'username':'xiaoming','password':'123456'}
r = requests.post('https://github.com/timeline.json',data=payload)
print r.text

(2)post请求发送文件(文件上传)

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
print r.text

5.返回值的说明

r.text
#Requests 会使用基于 HTTP 头部对响应的编码作出有根据的推测,就是编码好的文本内容

r.content
#Requests的返回二进制内容

r.json
#Requests的内置json解析器,如果返回的是json内容

6.定制请求头
为请求添加头部,给headers参数传递进去一个字典就好了

url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
print r.text

7.返回状态码的说明

r = requests.get('http://httpbin.org/get')
print r.status_code

8.带cookie的请求

url = 'http://httpbin.org/cookies'
#working就是实际通过浏览器抓到的一大坨的cookie的东西,cookies_are是固定格式,必须写
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
print r.text

#获取响应中的cookie
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
print r.cookies['example_cookie_name']

9.超时(不管什么网络库都有超时对不对)

#timeout=5
#在经过以 timeout参数设定的秒数时间之后停止等待响应,抛异常
requests.get('http://github.com', timeout=5)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,073评论 19 139
  • 目录: Python网络爬虫(一)- 入门基础Python网络爬虫(二)- urllib爬虫案例Python网络爬...
    一只写程序的猿阅读 14,431评论 17 68
  • 如果你把上篇多线程和多进程的文章搞定了,那么要恭喜你了 。你编写爬虫的能力上了一个崭新的台阶。不过,我们还不能沾沾...
    猴哥爱读书阅读 8,694评论 2 31
  • 今晚偶在中央一台看到综艺节目《欢乐中国人》中有一对年过八旬的军人老人讲述自己的一生,采用的是对话形式,六十年的“...
    faye26阅读 1,099评论 3 3
  • ## 精华界面不等高cell的搭建 1 . 精华界面搭建,tableview展示数据; 不等高cell(复杂界面)...
    龙龙_龙阅读 3,973评论 1 5

友情链接更多精彩内容