引言:
JSON数据格式和Requests模块在现代编程中扮演着不可或缺的角色。JSON作为一种轻量级的数据交换格式,广泛应用于Web服务之间的数据传输;而Requests库则是Python中最流行的HTTP客户端库,用于发起HTTP请求并与服务器交互。今天,我们将通过10个精选的代码示例,一同深入了解这两个重要工具的使用。
1.创建并解析JSON数据
import json
# 创建JSON数据
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data) # 将Python对象转换为JSON字符串
print(json_data) # 输出:{"name": "John", "age": 30, "city": "New York"}
# 解析JSON数据
json_string = '{"name": "Jane", "age": 28, "city": "San Francisco"}'
parsed_data = json.loads(json_string) # 将JSON字符串转换为Python字典
print(parsed_data) # 输出:{'name': 'Jane', 'age': 28, 'city': 'San Francisco'}
2.使用Requests发送GET请求
import requests
response = requests.get('https://api.github.com')
print(response.status_code) # 输出HTTP状态码,如:200
print(response.json()) # 输出响应体内容(假设响应是JSON格式)
# 保存完整的响应信息
with open('github_response.json', 'w') as f:
json.dump(response.json(), f)
3.发送带参数的GET请求
params = {'q': 'Python requests', 'sort': 'stars'}
response = requests.get('https://api.github.com/search/repositories', params=params)
repos = response.json()['items']
for repo in repos[:5]: # 打印前5个搜索结果
print(repo['full_name'])
4.发送POST请求
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post('http://httpbin.org/post', jsnotallow=payload, headers=headers)
print(response.json())
5.设置超时时间
requests.get('http://example.com', timeout=5) # 设置超时时间为5秒
6.处理Cookies
# 保存cookies
response = requests.get('http://example.com')
cookies = response.cookies
# 发送带有cookies的请求
requests.get('http://example.com', cookies=cookies)
7.自定义HTTP头部信息
headers = {'User-Agent': 'My-Custom-UA'}
response = requests.get('http://httpbin.org/headers', headers=headers)
print(response.text)
8.下载文件
url = 'https://example.com/image.jpg'
response = requests.get(url)
# 写入本地文件
with open('image.jpg', 'wb') as f:
f.write(response.content)
9.处理身份验证
from requests.auth import HTTPBasicAuth
response = requests.get('https://example.com/api', auth=HTTPBasicAuth('username', 'password'))
10.重试机制
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
# 创建一个重试策略
retry_strategy = Retry(
total=3,
status_forcelist=[429, 500, 502, 503, 504],
backoff_factor=1,
)
# 添加重试策略到适配器
adapter = HTTPAdapter(max_retries=retry_strategy)
# 将适配器添加到会话
session = requests.Session()
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.get('https://example.com')
结语:
通过上述10个Python中JSON数据格式与Requests模块的实战示例,相信您对它们的使用有了更为深入的理解。熟练掌握这两种工具将极大提升您在Web开发、API调用等方面的生产力。请持续关注我们的公众号,获取更多Python和其他编程主题的精彩内容!