python 之requests库使用汇总

1、GET和POST介绍
  (1)GET请求: (HTTP默认的请求方法就是GET)
       * 没有请求体
       * 数据必须在1K之内!
       * GET请求数据会暴露在浏览器的地址栏中

   (2)GET请求常用的操作:
         1. 在浏览器的地址栏中直接给出URL,那么就一定是GET请求
         2. 点击页面上的超链接也一定是GET请求
         3. 提交表单时,表单默认使用GET请求,但可以设置为POST

   (3)POST请求
      (1). 数据不会出现在地址栏中
      (2). 数据的大小没有上限
      (3). 有请求体
      (4). 请求体中如果存在中文,会使用URL编码!

发送post json可以用json=data,需要用json.dumps转换参数;
发送json请求
requests默认使用application/x-www-form-urlencoded对POST数据编码
params = {'key': 'value'}
r = requests.post(url, json=params) # 内部自动序列化为JSON


响应

# response响应
print(response.status_code)  # 获取响应状态码
print(response.url)  # 获取url地址
print(response.text)  # 获取文本
print(response.content)  # 获取二进制流
print(response.headers)  # 获取页面请求头信息
print(response.history)  # 上一次跳转的地址
print(response.cookies)  # # 获取cookies信息
print(response.cookies.get_dict())  # 获取cookies信息转换成字典
print(response.cookies.items())  # 获取cookies信息转换成字典
print(response.encoding)  # 字符编码
print(response.elapsed)  # 访问时间

1.超时设置
# 两种超时:float or tuple
# timeout=0.1  # 代表接收数据的超时时间
# timeout=(0.1,0.2)  # 0.1代表链接超时  0.2代表接收数据的超时时间
import requests
response = requests.get('https://www.baidu.com',
                        timeout=0.0001)

2.代理:
proxies = {'http':'ip1','https':'ip2' }
requests.get('url',proxies=proxies)

# 官网链接: http://docs.python-requests.org/en/master/user/advanced/#proxies

# 代理设置:先发送请求给代理,然后由代理帮忙发送(封ip是常见的事情)
import requests
proxies={
    # 带用户名密码的代理,@符号前是用户名与密码
    'http':'http://tank:123@localhost:9527',
    'http':'http://localhost:9527',
    'https':'https://localhost:9527',
}
response=requests.get('https://www.12306.cn',
                     proxies=proxies)
print(response.status_code)


# 支持socks代理,安装:pip install requests[socks]
import requests
proxies = {
    'http': 'socks5://user:pass@host:port',
    'https': 'socks5://user:pass@host:port'
}
respone=requests.get('https://www.12306.cn',
                     proxies=proxies)

print(respone.status_code)


3.cookies:
cs = {'token': '12345', 'status': 'working'}
r = requests.get(url, cookies=cs)

4.上传文件
upload_files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=upload_files)

posted @ 2020-03-20 15:10  Golover  阅读(344)  评论(0编辑  收藏  举报