码迷,mamicode.com
首页 > 编程语言 > 详细

python requests库学习

时间:2017-08-30 21:47:14      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:his   pypi   orm   load   美女   tun   exce   from   方便   

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 
 7 def build_url(endpoint):
 8     return /.join([URL, endpoint])
 9 
10 def better_print(json_str):
11     return  json.dumps(json.loads(json_str), indent=4)
12 
13 def request_method():
14     response = requests.get(build_url(users/liwenchi123000))
15     print(better_print(response.text))
16 
17 if __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 
 3 def timeout_request():
 4     try:
 5         response = requests.get(https://www.baidu.com/, timeout=0.05)
 6     except exceptions.Timeout as e:
 7         print(e)
 8     else:
 9         print(response.text)
10 
11 if __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
 8     print(prepared.headers)
 9     print(prepared.body)
10     # 现在发送,并设置延迟时间
11     response = s.send(prepared, timeout=5)
12     # 检查返回值
13     print(response.status_code)
14     print(response.request.headers)
15     print(response.text)
16 
17 if __name__ == __main__:
18     hard_request()

常见API

response

status_code 响应码

reason 相应结果

headers 头信息

url 地址

history 经历了什么

elapsed

request

encoding 编码格式

raw

content

text

json

 

python requests库学习

标签:his   pypi   orm   load   美女   tun   exce   from   方便   

原文地址:http://www.cnblogs.com/liwenchi/p/7455209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!