用request第三方库批量下载百度图片,要求可以多页下载,并放入到相应文件夹。使用pillow第三方库,将获取到的图片批量添加水印文字(添加的文字要有个人信息,学号姓名等)
时间: 2024-06-09 20:07:06 浏览: 153
以下是实现该功能的Python代码:
```python
import os
import requests
from PIL import Image, ImageDraw, ImageFont
# 学生个人信息
student_info = {
'name': '张三',
'student_id': '202100001',
}
# 下载图片
def download_images(keyword, page_num, save_dir):
os.makedirs(save_dir, exist_ok=True) # 创建保存图片的文件夹
for i in range(page_num):
url = f'https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord={keyword}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&word={keyword}&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=&fr=&pn={i*30}&rn=30&gsm=1e&1527089699255='
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers).json()
for j, item in enumerate(response['data']):
if item.get('thumbURL'):
image_url = item['thumbURL']
response = requests.get(image_url)
with open(os.path.join(save_dir, f'{i*30+j}.jpg'), 'wb') as f:
f.write(response.content)
# 添加水印
def add_watermark(image_path, text, save_path):
font = ImageFont.truetype('arial.ttf', 20)
with Image.open(image_path) as image:
draw = ImageDraw.Draw(image)
draw.text((10, 10), text, font=font, fill=(255, 255, 255, 128))
image.save(save_path)
# 下载并添加水印
def download_and_watermark(keyword, page_num, save_dir):
download_images(keyword, page_num, save_dir)
for filename in os.listdir(save_dir):
image_path = os.path.join(save_dir, filename)
save_path = os.path.join(save_dir, f'watermark_{filename}')
add_watermark(image_path, f'{student_info["name"]} {student_info["student_id"]}', save_path)
# 测试代码
if __name__ == '__main__':
download_and_watermark('猫', 2, 'cat_images')
```
该代码会下载百度图片搜索结果中关键词为“猫”的前两页图片,并将图片添加上学生个人信息的水印,最终保存在`cat_images`文件夹中。你可以根据自己的需要更改关键词、页数和保存文件夹等参数。
阅读全文