使用selenium将长文章批量截图保存

导读:本篇文章讲解 使用selenium将长文章批量截图保存,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

有时候需要将公众号的文章截图保存下来,遇到长文章还需要批量截图保存,而且公众号的文章挺多的!逐个打开截图保存费时又费神!

最开始有两个思路的,

第一,创建一张空白的图片,然后获取文章的html,最后在打印在图片上,完事后再切割,但是根据以往经验,在打印在图片上的时候,未必和实际html 一致,而且容易走位,调试也繁琐。所以可以忽略这种方法

第二,直接调用浏览器,然后截图!在python 的学习大纲里面,有个框架叫selenium,是测试人员用于web 自动化测试的!

查看相关资料,对于web 开发人员比较容易上手。最基本的用法就是定位一个元素,然后对该元素一些操作,比如输入内容、click()、change()等等,最重要的是还可以截图呢!

安装:

pip install selenium

我直接贴代码:

# 打开浏览器
from io import BytesIO
from time import sleep

from pil import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
import math

driver = webdriver.Chrome()

# 设定每个截图的height 是800
iamge_height = 800

# 设定load截图高度 用于load 图片时候用
load_image_height = 500

# 加载网页
driver.get('https://mp.weixin.qq.com/s/omg5kObXHEtf6zevOgPsQw')
filename = driver.find_element(By.ID, 'activity-name').text
# 根据调整zoom 实现缩放浏览器
driver.execute_script("document.body.style.zoom='0.7'")
# 设置浏览器大小
driver.set_window_size(375, iamge_height)
# 获取的页面的高度
page_height = driver.execute_script("return document.getElementById('page-content').scrollHeight")
# 计算有几张图片,即系遍历多少次
num = math.ceil(page_height // iamge_height)
loadImageNum = math.ceil(page_height // load_image_height)

# load 所有图片
readloop = 1
while readloop <= loadImageNum:
    sleep(1)
    driver.execute_script(f'document.documentElement.scrollTop={(load_image_height) * (readloop)};')
    readloop = readloop + 1

# 重新回到顶部
driver.execute_script('document.documentElement.scrollTop=0;')

# 重新load 并下载 因为最后footer 部分是多余的,所以有1张可以忽略
loop = 1
while loop <= (num - 1):
    sleep(1)
    screenshot = driver.get_screenshot_as_png()
    screenshot = Image.open(BytesIO(screenshot))
    driver.get_screenshot_as_file('./screenshots/'+filename + '(' + str(loop) + ').png')
    # 向下滚动iamge_height,再截图
    driver.execute_script(f'document.documentElement.scrollTop={(iamge_height - 150) * (loop)};')
    loop = loop + 1

driver.close()

为什么要while 两次,因为我截图公众号的文章,文章中的图片需要你到该区域,才会load 出来的,如果直接截图保存,图片会显示不到,所以我先while 一次,让它load出所有的图片,然后再截图!

结果如下:

使用selenium将长文章批量截图保存

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/97969.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!