标签:编码 app tco etc 允许 header div import util
1、发送请求
import requests
r = requests.get("https://www.baidu.com/")
print(r)
r = requests.post(‘http://httpbin.org/post‘, data = {‘key‘:‘value‘})
print(r)
"""output:<Response [200]>
"""
2、传递URL参数。如果你想传递 key1=value1
和 key2=value2
到https://www.baidu.com/,Requests 允许你使用 params
关键字参数,以一个字符串字典来提供这些参数。
import requests payload = {"key1":"value1", "key2":"value2"} r = requests.get("https://www.baidu.com/", params=payload) print(r.url) """output:https://www.baidu.com/?key1=value1&key2=value2 """
3 、响应内容
import requests r = requests.get(‘https://leetcode-cn.com/‘) print(r.text)
4、定制请求头:如果你想为请求添加 HTTP 头部,只要简单地传递一个 dict
给 headers
参数就可以了。
import requests url = "https://leetcode-cn.com/" headers = {‘user-agent‘: ‘my-app/0.0.1‘} r = requests.get(url, headers = headers) print(r.headers)
5、发送一些编码为表单形式的数据,要实现这个,只需简单地传递一个字典给 data 参数。你的数据字典在发出请求时会自动编码为表单形式。
import requests
payload = {‘key1‘:‘value‘,‘key2‘:‘value2‘}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)
"""
output: "form": {
"key1": "value",
"key2": "value2"
},
"""
6、检测响应码。
import requests r = requests.get("https://www.baidu.com/") print(r.status_code) """ output:200
import requests bad_r = requests.get(‘http://httpbin.org/status/404‘) print(bad_r.status_code) print(bad_r.raise_for_status()) """ output:404 output:requests.exceptions.HTTPError: 404 Client Error """
7、响应头。
import requests r = requests.get("https://www.baidu.com/") print(r.headers["content-type"]) """ output:text/html """
标签:编码 app tco etc 允许 header div import util
原文地址:https://www.cnblogs.com/yijierui/p/13222126.html