JSON数据格式和Requests模块在现代编程中扮演着不可或缺的角色。JSON作为一种轻量级的数据交换格式,广泛应用于Web服务之间的数据传输;而Requests库则是Python中最流行的HTTP客户端库,用于发起HTTP请求并与服务器交互。今天,我们将通过10个精选的代码示例,一同深入了解这两个重要工具的使用。
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 requestsresponse = requests.get('https://api.github.com')print(response.status_code) # 输出HTTP状态码,如:200print(response.json()) # 输出响应体内容(假设响应是JSON格式)# 保存完整的响应信息with open('github_response.json', 'w') as f: json.dump(response.json(), f)
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'])
payload = {'key1': 'value1', 'key2': 'value2'}headers = {'Content-Type': 'application/json'}response = requests.post('http://httpbin.org/post', jsnotallow=payload, headers=headers)print(response.json())
requests.get('http://example.com', timeout=5) # 设置超时时间为5秒
# 保存cookiesresponse = requests.get('http://example.com')cookies = response.cookies# 发送带有cookies的请求requests.get('http://example.com', cookies=cookies)
headers = {'User-Agent': 'My-Custom-UA'}response = requests.get('http://httpbin.org/headers', headers=headers)print(response.text)
url = 'https://example.com/image.jpg'response = requests.get(url)# 写入本地文件with open('image.jpg', 'wb') as f: f.write(response.content)
from requests.auth import HTTPBasicAuthresponse = requests.get('https://example.com/api', auth=HTTPBasicAuth('username', 'password'))
from requests.adapters import HTTPAdapterfrom 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和其他编程主题的精彩内容!
本文链接:http://www.28at.com/showinfo-26-83616-0.html揭秘Python中的JSON数据格式与Requests模块
声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com
上一篇: C# 中的 HTTP 请求