本文介绍了python中发送http请求的两种方法:内置的urllib库和第三方requests库。urllib提供基础功能,而requests库更简单强大,支持get/post请求、参数传递、请求头设置等功能。
本文通过天气api示例演示了实际应用,并提供了超时设置、错误处理和json解析等实用技巧。推荐大多数场景使用requests库,同时强调了异常处理的重要性。这些方法为获取网络数据和与web服务交互提供了基础工具。
想象一下,你想要从网上获取一些信息——比如今天的天气、最新的新闻或者一张图片。这就像给网站写一封信,然后等待回信。python就是你的贴心邮差,帮你轻松完成这个收发过程。
最简单的方式:使用urllib(python内置)
python自带了一个叫urllib的库,就像你手机里自带的短信应用,不需要额外安装。
import urllib.request
# 发送一个简单的get请求
response = urllib.request.urlopen('https://www.example.com')
print(response.read().decode('utf-8')) # 读取并解码响应内容
推荐方式:使用requests库(更简单强大)
虽然python自带工具,但requests库就像一款智能邮件应用,让一切变得更加简单直观。
第一步:安装requests
pip install requests
第二步:发送各种类型的请求
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)
实际应用示例:获取天气信息
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')
小贴士和注意事项
超时设置:总是设置合理的超时时间,避免程序卡死
requests.get(url, timeout=5)
错误处理:使用try-except块捕获可能的异常
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.requestexception as e:
print(f"请求出错: {e}")
json处理:现代api大多返回json格式,requests可以直接解析
data = response.json()
总结
- 简单需求:使用python内置的urllib
- 大多数情况:使用requests库,它更简单、更强大
- 记住设置超时和处理异常
- 现代web api大多使用json格式,requests可以轻松处理
现在你已经掌握了用python发送http请求的基本方法!就像学会了写电子邮件一样,你可以开始探索互联网上的各种数据和服务了。
到此这篇关于python使用urllib和requests发送http请求的方法详解的文章就介绍到这了,更多相关python发送http请求内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论