想象一下,你想要从网上获取一些信息——比如今天的天气、最新的新闻或者一张图片。这就像给网站写一封信,然后等待回信。Python就是你的贴心邮差,帮你轻松完成这个收发过程。
最简单的方式:使用urllib(Python内置)
Python自带了一个叫urllib的库,就像你手机里自带的短信应用,不需要额外安装。
importurllib.request# 发送一个简单的GET请求response=urllib.request.urlopen('https://www.example.com')print(response.read().decode('utf-8'))# 读取并解码响应内容推荐方式:使用requests库(更简单强大)
虽然Python自带工具,但requests库就像一款智能邮件应用,让一切变得更加简单直观。
第一步:安装requests
pipinstallrequests第二步:发送各种类型的请求
importrequests# 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)实际应用示例:获取天气信息
importrequestsdefget_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")exceptrequests.exceptions.RequestExceptionase:print(f"获取天气信息失败:{e}")# 使用函数get_weather('Beijing')小贴士和注意事项
超时设置:总是设置合理的超时时间,避免程序卡死
requests.get(url,timeout=5)错误处理:使用try-except块捕获可能的异常
try:response=requests.get(url)response.raise_for_status()exceptrequests.exceptions.RequestExceptionase:print(f"请求出错:{e}")JSON处理:现代API大多返回JSON格式,requests可以直接解析
data=response.json()
总结
- 简单需求:使用Python内置的
urllib - 大多数情况:使用
requests库,它更简单、更强大 - 记住设置超时和处理异常
- 现代Web API大多使用JSON格式,requests可以轻松处理
现在你已经掌握了用Python发送HTTP请求的基本方法!就像学会了写电子邮件一样,你可以开始探索互联网上的各种数据和服务了。
Happy coding! 🚀