Post

0201request

request

安装

pip3 install request

基本库的使用

一、get/post方法中参数

参数描述其他
files上传文件(仅适用post)f = {‘file’: open(‘favicon.ico’, ‘rb’)}
dataget方法中data参数拼接在url中,post则存放在表单中(form)data = {‘name’: ‘germey’, ‘age’: ‘25’}
cookies设置cookiesjar=requests.cookies.RequestsCookiesJar()
jar.set(key,value)
headers请求头headers={‘User-Agent’:’’,’Cookie’:’’}。可通过headers设置Cookie
timeout设置超时:链接+读取的总和单位秒
auth身份认证from requests.auth import HTTPBasicAuth
auth=HTTPBasicAuth(name,pwd)

auth=(name,pwd)
proxies代理1.http代理:p={“http”:”http://x.x.x.x:1233”,….}

2.socks代理:安装socks库(pip3 install “requests[socks]”)
p={“http”:”soksS://user:password&hosts:port”,…}

二、Session维持 p57

1
2
3
4
s = requests.Session()
s.post('https://httpbin.org/cookies/set/number/123456789')#获取url的Session(cookie)
r = s.post('https://httpbin.org/cookies') #维持上面url的Session(自动设置cookie)请求当前url
print(r.text)

三、Prepared Request p62

1
2
3
4
5
from requests import Request,Session
s=Session()
req=Request('POST',url,data,headers...)
prepared=s.prepare_requests(req)
r=s.send(prepared)

四、requests.models.Response中text和content差别

  • text返回文本
  • content返回二进制

    1
    2
    3
    
    r = requests.get('https://github.com/favicon.ico')
    print(r.text)
    print(r.content)
    

五、ssl证书验证

  • 取消https ssl验证
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 方法一:设置`ssl._create_default_https_context`
  import ssl
  ssl._create_default_https_context=ssl._create_unverified_context

# 方法二:调用`requests库的get、post方法增加参数verify=False`
  import requests

  #捕获警告信息2中方法(不捕获会在控制台显示)
  # ① p60
  from requests.packages import urllib3
  urllib3.disable_warnings()

  # ②
  import logging
  logging.captureWarnings(True)#捕获警告信息。上面的verify=False取消ssl证书验证

  r=requests.get(url,verify=False)#加参数verify=False
  • 导入证书验证
1
2
response = requests.get(url, cert=('/path/server.crt', '/path/server.key'))
#需要有 crt 和 key 文件,并且指定它们的路径。另外注意,本地私有证书的 key 必须是解密状态,加密状态的 key 是不支持的。
This post is licensed under CC BY 4.0 by the author.