亲爱的小伙伴们~今天让我来带大家认识一个超级好用的Python库:Requests!它就像是我们在互联网上的小助手,帮我们获取各种网页的内容,简直不要太方便啦!不管是下载图片、抓取数据,还是调用API接口,都可以轻松搞定呢!(●'?'●)
一、初识Requests酱
首先需要安装这个小可爱,只需要在命令行输入:
pip install requests
安装好之后,我们就可以开始使用啦!先来个最简单的GET请求示例:
import requests
# 发送GET请求到百度
response = requests.get('https://www.baidu.com')
print(f'状态码: {response.status_code}')
print(f'网页编码: {response.encoding}')
小贴士:状态码200表示请求成功哦!如果遇到404就是页面找不到啦~
二、请求方式大集合
Requests不只会GET哦,还有其他几种常用的请求方式:
# GET请求带参数
params = {
'key1': 'value1',
'key2': 'value2'
}
response = requests.get('http://httpbin.org/get', params=params)
# POST请求发送数据
data = {
'username': 'kawaii',
'password': '123456'
}
response = requests.post('http://httpbin.org/post', data=data)
三、自定义请求头小技巧
有时候网站会限制爬虫访问,这时候我们就要扮装成浏览器啦:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get('https://www.example.com', headers=headers)
四、Cookie和Session的小秘密
有些网站需要登录才能访问,这时候就需要处理Cookie啦:
# 创建会话对象
session = requests.Session()
# 登录
login_data = {
'username': 'kawaii_user',
'password': 'super_secret'
}
session.post('http://example.com/login', data=login_data)
# 访问需要登录的页面
response = session.get('http://example.com/profile')
小贴士:用Session可以自动保持Cookie,不用每次都手动处理呢!
五、下载文件小能手
来看看如何下载可爱的图片:
def download_image(url, filename):
response = requests.get(url, stream=True)
if response.status_code == 200:
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
f.write(chunk)
print(f'图片{filename}下载完成啦~')
else:
print('哎呀,下载失败了呢~')
六、异常处理要温柔
网络请求可能会遇到各种问题,要温柔地处理它们:
try:
response = requests.get('https://example.com', timeout=5)
response.raise_for_status() # 检查是否请求成功
except requests.exceptions.RequestException as e:
print(f'哎呀,出错啦:{e}')
实战小练习
来试试抓取一个天气API的数据吧:
def get_weather(city):
url = f'http://api.weather.com/v1/weather?city={city}'
try:
response = requests.get(url)
data = response.json()
print(f'{city}的天气是:{data["weather"]}')
print(f'温度是:{data["temperature"]}℃')
except:
print('抱歉呢,获取天气信息失败了~')
小伙伴们,今天的Python学习之旅就到这里啦!记得动手敲代码,有问题随时在评论区问我哦。使用Requests真的超级简单吧?赶快试试用它来写一个自己的小爬虫吧!祝大家学习愉快,Python学习节节高!(?????)