用requests或者bs4第三方库批量下载百度图片,要求可以多页下载,并放入到相应文件夹。使用pillow第三方库,将获取到的图片批量添加水印文字(添加的文字要有个人信息,学号姓名等)
时间: 2023-07-15 12:11:37 浏览: 51
首先,我们需要了解一下百度图片搜索的URL格式。以搜索“猫”为例,其URL为:
https://image.baidu.com/search/index?tn=baiduimage&word=猫
其中,word参数后面的值就是我们要搜索的关键词。
接下来,我们可以使用requests和bs4第三方库来批量下载百度图片。具体代码如下:
```python
import os
import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse
def download_images(keyword, num_pages, save_path):
# 创建保存图片的文件夹
if not os.path.exists(save_path):
os.makedirs(save_path)
# 循环下载每一页的图片
for i in range(num_pages):
url = f"https://image.baidu.com/search/index?tn=baiduimage&word={keyword}&pn={i*30}"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 获取每张图片的URL,并下载保存
for img in soup.find_all("img"):
img_url = img.get("src")
if not img_url:
continue
try:
response = requests.get(img_url, stream=True)
filename = os.path.join(save_path, os.path.basename(urlparse(img_url).path))
with open(filename, "wb") as f:
for chunk in response.iter_content(1024):
f.write(chunk)
except:
continue
```
其中,keyword为要搜索的关键词,num_pages为要下载的页数,save_path为保存图片的文件夹路径。
接下来,我们可以使用Pillow第三方库来批量添加水印文字。具体代码如下:
```python
from PIL import Image, ImageDraw, ImageFont
def add_watermark(image_path, text):
# 打开图片
image = Image.open(image_path)
# 获取字体
font = ImageFont.truetype("arial.ttf", size=20)
# 添加水印文字
draw = ImageDraw.Draw(image)
draw.text((10, 10), text, font=font, fill=(255, 255, 255, 128))
# 保存图片
image.save(image_path)
```
其中,image_path为要添加水印的图片路径,text为要添加的水印文字。
最后,我们可以将上述两个函数结合起来,实现批量下载百度图片并添加水印的功能。具体代码如下:
```python
def download_and_add_watermark(keyword, num_pages, save_path, text):
# 下载图片
download_images(keyword, num_pages, save_path)
# 添加水印
for filename in os.listdir(save_path):
if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png"):
image_path = os.path.join(save_path, filename)
add_watermark(image_path, text)
```
其中,text为要添加的水印文字,例如“学号:123456,姓名:张三”。
调用方式为:
```python
download_and_add_watermark("猫", 3, "./images", "学号:123456,姓名:张三")
```
其中,第一个参数为要搜索的关键词,第二个参数为要下载的页数,第三个参数为保存图片的文件夹路径,第四个参数为要添加的水印文字。