返回

历史上的今天:用Python自动制作宣传图片

后端

大家好,今天分享一个通过 Python 自动创建相关图片的教程,而这个相关图片就是《历史上的今天》。

在日常工作中,我们经常会需要用到宣传图片,而历史上的今天这种类型图片的需求量很大,但是如果我们每次都需要手动制作的话,那将是非常耗时的。

所以,今天我们就来学习一下如何使用 Python 自动制作历史上的今天宣传图片。

1. 准备工作

在开始之前,我们需要准备以下几个东西:

  • Python 3.6 或更高版本
  • Pillow 库
  • requests 库
  • beautifulsoup4 库
  • 一个文本文件,其中包含您想要创建图片的日期

2. 代码实现

现在,我们就可以开始编写代码了。

from PIL import Image, ImageDraw, ImageFont
import requests
from bs4 import BeautifulSoup

# 读取日期文件
with open('dates.txt', 'r') as f:
    dates = f.readlines()

# 循环每个日期
for date in dates:
    # 从网络上抓取信息
    url = 'https://www.history.com/this-day-in-history/' + date.strip()
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')

    # 获取事件标题和
    title = soup.find('h1', class_='headline').text
    description = soup.find('div', class_='article-synopsis').text

    # 创建图像
    image = Image.new('RGB', (1280, 720), (255, 255, 255))
    draw = ImageDraw.Draw(image)

    # 添加标题
    font = ImageFont.truetype('Arial.ttf', 48)
    draw.text((100, 100), title, font=font, fill=(0, 0, 0))

    # 添加
    font = ImageFont.truetype('Arial.ttf', 24)
    draw.text((100, 200), description, font=font, fill=(0, 0, 0))

    # 保存图像
    image.save('history_of_' + date.strip() + '.png')

# 保存成功提示
print('图片生成成功!')

3. 运行代码

将上述代码保存为一个 Python 文件,然后在终端中运行它。

python history_of_today.py

运行完成后,您将在当前目录中看到一个名为“history_of_today”的文件夹,其中包含您指定日期的历史上的今天宣传图片。

4. 结语

这就是如何使用 Python 自动制作历史上的今天宣传图片。希望这个教程对您有所帮助。

如果您有任何问题,请随时留言。