python requests库学习
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python requests库学习,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2293字,纯文字阅读大概需要4分钟。
内容图文
1.先bia一个国内镜像吧
用法很简单 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests
2.大二的时候受到小甲鱼的蛊惑,拿urllib爬美女写真图。。。。。。真的是超级麻烦(其实也没多麻烦)
3.前段时间听说有个很好用的包‘requests’,最近开学学计算机网络和互联网程序设计,于是就想起了这个,准备探索一下
先大概看了一下,真的很方便,因为之前老遇到转码的问题。。。一窍不通。反正就是bytes()、decode()、encode(),之间互相试。。。。。。
而这个真的就很简单了,拿到response以后直接.text就得到str了
1 # -*- coding: utf-8 -*- 2 import json 3 import requests 4 5 URL = ‘https://api.github.com‘ 6 7def build_url(endpoint): 8return‘/‘.join([URL, endpoint]) 910def better_print(json_str): 11return json.dumps(json.loads(json_str), indent=4) 1213def request_method(): 14 response = requests.get(build_url(‘users/liwenchi123000‘)) 15print(better_print(response.text)) 1617if__name__ == ‘__main__‘: 18 request_method()
这个就是用requests.get()方法,利用github的一个查看用户的api来得到一些用户信息,当时是保密的。
带参数的请求,这个我自己还没有试,先看文档写下来吧
普通的请求
response = requests.get(URL, params={‘param1‘:‘value1‘,‘param2‘:‘value2‘})
表单参数提交
‘ Content-Type: application/x-www-form-urlencoded ‘ response = requests.post(URL, data={‘param1‘:‘value1‘, ‘param2‘:‘value2‘})
json参数提交(github就是用的这种)
‘ Content-Type: application/json ‘ response = requests.post(URL, json={‘param1‘: ‘value1‘, ‘param2‘: ‘value2‘})
还有异常检测
例如下面这个超时检测
1 from requests import exceptions 2 3def timeout_request(): 4try: 5 response = requests.get(‘https://www.baidu.com/‘, timeout=0.05) 6except exceptions.Timeout as e: 7print(e) 8else: 9print(response.text) 1011if__name__ == ‘__main__‘: 12 timeout_request()
0.05秒还是有点快的,显示的结果是
HTTPSConnectionPool(host=‘www.baidu.com‘, port=443): Read timed out. (read timeout=0.05)
如何自定义一个request
1 def hard_request(): 2 from requests import Request, Session 3 s = Session() 4 headers = {‘User-Agent‘:‘fake1.3.4‘} 5 request = Request(‘GET‘, build_url(‘user/emails‘), auth=(‘liwenchi123000‘,‘******‘), headers=headers) 6 prepared = request.prepare() 7# 先准备一个request但是不发出去,先看一下它的headers和body 8print(prepared.headers) 9print(prepared.body) 10# 现在发送,并设置延迟时间11 response = s.send(prepared, timeout=5) 12# 检查返回值13print(response.status_code) 14print(response.request.headers) 15print(response.text) 1617if__name__ == ‘__main__‘: 18 hard_request()
常见API
response
status_code 响应码
reason 相应结果
headers 头信息
url 地址
history 经历了什么
elapsed
request
encoding 编码格式
raw
content
text
json
原文:http://www.cnblogs.com/liwenchi/p/7455209.html
内容总结
以上是互联网集市为您收集整理的python requests库学习全部内容,希望文章能够帮你解决python requests库学习所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。