request模块 一基础部分

一、HTTP请求  

通过requests发送网络请求,方法有get post put delete head options

import requests
r=requests.get("http://github.com/timeline.json")
print(r.text)
r=requests.post("http://httpbin.org/post")
print(r.text)

二、传递URL参数

如果为url字符串传递数据,手工构建url那么数据就会以键值对的方式存在URL中,字典中的None不会被添加到URL的查询字符串里面

import requests
payload={"key1":"value1","key2":"value2","key3":("value2",)}
r=requests.get("http://httpbin.org/get",params=payload)
print(r.text)  #获取相应内容
print(r.url) #http://httpbin.org/get?key1=value1&key2=value2&key3=value2

三、相应内容

1、自动编码的获取相应内容

r.text

2、二进制方式相应内容

r.content

3、获取传递的url

r.url

4、获取json响应内容

r.json()

注意:

a、如果json解压失败,会抛出一个异常

b、成功调用并不意味着响应成功,所以要用

r.raise_for_status()成功返回None或者r.status_code验证成功返回200

5、获取响应头

r.headers

由于响应头是字典形式,所以可以用get等字典方式获取内容

5、获取请求对象列表

r.history

四、定制请求

请求做成数据流文档 

1、定制请求头,直接传递dict。给headers参数就可以

如:

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

2、复杂的POST请求

a、要发送一些表单形式的数据传递参数data就可以,这个参数可以是元祖,列表

如:

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

 b、可以直接使用json参数传递

import requests
import json
payload={'some':'data'}


r=requests.post("https://api.github.com/some/endpoint",json=payload)
print(r.text)

3、post多部分编码的文件,这里requests里面可以写入请求头

import requests
url="http://httpbin.org/post"
files={"file":open("a.txt","rb")}

r=requests.post(url,files=files)
print(r.text)、

五、相应状态码

1、查询相应吗

r.status_code

2、抛出异常

r.raise_for_status()

六、cookie

1、获取cookie

import requests
url='http://www.baidu.com'


r=requests.get(url)
print(r.cookies)

2、设置cookie

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text

 3、超时

r=requests.get(url,timeout=1)

 超时只对连接有效,如果在timeout时间没有应答,会引发异常

原文地址:https://www.cnblogs.com/pyrene/p/7486612.html