本文通过天气API示例演示了实际应用,并提供了超时设置、错误处理和JSON解析等实用技巧。推荐大多数场景使用requests库,同时强调了异常处理的重要性。这些方法为获取网络数据和与Web服务交互提供了基础工具。
想象一下,你想要从网上获取一些信息——比如今天的天气、最新的新闻或者一张图片。这就像给网站写一封信,然后等待回信。Python就是你的贴心邮差,帮你轻松完成这个收发过程。
Python自带了一个叫urllib的库,就像你手机里自带的短信应用,不需要额外安装。
|
1 2 3 4 5 |
import urllib.request
# 发送一个简单的GET请求 response = urllib.request.urlopen('https://www.example.com') print(response.read().decode('utf-8')) # 读取并解码响应内容 |
虽然Python自带工具,但requests库就像一款智能邮件应用,让一切变得更加简单直观。
第一步:安装requests
|
1 |
pip install requests |
第二步:发送各种类型的请求
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import requests
# 1. 简单的GET请求(获取信息) response = requests.get('https://api.github.com') print(f"状态码: {response.status_code}") # 200表示成功 print(response.text) # 获取网页内容
# 2. 带参数的GET请求(像在搜索框里输入内容) params = {'key1': 'value1', 'key2': 'value2'} response = requests.get('https://httpbin.org/get', params=params) print(response.url) # 查看实际请求的URL
# 3. POST请求(提交信息,像填写表单) data = {'username': 'user', 'password': 'pass'} response = requests.post('https://httpbin.org/post', data=data) print(response.json()) # 以JSON格式查看响应
# 4. 自定义请求头(像添加特别说明) headers = {'User-Agent': 'My-Python-App/1.0'} response = requests.get('https://httpbin.org/user-agent', headers=headers) print(response.text) |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import requests
def get_weather(city): # 使用一个免费的天气API(实际使用需要申请API密钥) api_key = "你的API密钥" url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
try: response = requests.get(url, timeout=5) # 5秒超时 response.raise_for_status() # 如果请求失败会抛出异常
weather_data = response.json() print(f"{city}的天气: {weather_data['weather'][0]['description']}") print(f"温度: {weather_data['main']['temp']}K")
except requests.exceptions.RequestException as e: print(f"获取天气信息失败: {e}")
# 使用函数 get_weather('Beijing') |
超时设置:总是设置合理的超时时间,避免程序卡死
|
1 |
requests.get(url, timeout=5) |
错误处理:使用try-except块捕获可能的异常
|
1 2 3 4 5 |
try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"请求出错: {e}") |
JSON处理:现代API大多返回JSON格式,requests可以直接解析
|
1 |
data = response.json() |
现在你已经掌握了用Python发送HTTP请求的基本方法!就像学会了写电子邮件一样,你可以开始探索互联网上的各种数据和服务了。