requests与get请求

长孙阳嘉
2023-12-01
# get请求
r = requests.get('http://httpbin.org/get')

# 传递参数
params = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('http://httpbin.org/get', params=params)
"""
r.text 返回编码解析的结果
r.content返回二进制结果
r.json()返回字典,可能抛出异常
r.status_code
r.raw返回原始socket response,需要加参数stream=True
"""
print(r.status_code)
print(r.text)
print(r.content)
print(r.json())

# raw 返回原始socket response
r = requests.get('http://httpbin.org/get', stream=True)
print(r.raw)
with open("httpbin.txt", 'w') as wr:
    wr.write(r.raw.read().decode('utf8'))

# 传递headers
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get('http://httpbin.org/get', headers=headers)

# 传递cookies
url = 'http://httpbin.org/cookies'
r = requests.get(url, cookies=dict(cookies_equ='cache info'))
r.text

# 发送POST请求
# 传递表单
#
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)
 类似资料: