目录
requests?是 Python 中的一个非常流行的 HTTP 客户端库,用于发送 HTTP 请求。它使得发送 GET、POST、PUT、DELETE 等请求变得非常简单。
import requests ?
??
# 发送 GET 请求 ?
response = requests.get('https://www.baidu.com') ?
??
# 打印响应内容 ?
print(response.text) ?
??
# 发送 POST 请求 ?
data = {'key1': 'value1', 'key2': 'value2'} ?
response = requests.post('https://www.baidu.com', data=data) ?
传递cookie信息
cookies = {'cookie_name': 'cookie_value'} ?
??
response = requests.post('https://www.baidu.com', cookies=cookies)?
设置代理信息:
??
proxies = { ?
? ? 'http': 'http://10.10.1.10:3128', ?
? ? 'https': 'http://10.10.1.10:1080', ?
} ?
??
response = requests.post('https://www.baidu.com', proxies=proxies) ?
设置超时时间:
timeout = 30.0? # 设置超时时间为30秒 ?
try: ?
? ? response = requests.get(url, timeout=timeout) ?
? ? print(response.text) ?
except requests.exceptions.Timeout: ?
? ? print('请求超时')
发送文件信息:
url = 'https://api.example.com/upload' ?
file_path = 'path/to/file.txt' ?
with open(file_path, 'rb') as file: ?
? ? files = {'file': ('file.txt', file, 'text/plain')} ?
? ? response = requests.post(url, files=files) ?
??
# 打印响应内容 ?
print(response.text)
?
import requests ?
??
url = 'https://www.baidu.com' ?
data = {'key1': 'value1', 'key2': 'value2'} ?
headers = {'Content-Type': 'application/json'} ?
??
response = requests.put(url, data=data, headers=headers) ?
??
print(response.text)
?
import requests
url = 'https://www.baidu.com'
headers = {'Content-Type': 'application/json'}
response = requests.delete(url, headers=headers)
print(response.text)
??
# 获取响应状态码 ?
status_code = response.status_code ?
print(f'Status Code: {status_code}') ?
??
# 获取响应内容 ?
content = response.content ?
print(f'Content: {content}') ?
??
# 获取响应文本 ?
text = response.text ?
print(f'Text: {text}')