Python+Selenium无头浏览器实现网页截图

一、背景

最近有个需求,就是需要登录系统,针对系统的流程数据,有一个工作流程图或者说叫审批流程图。每个阶段都有相对应的人员审批、评论信息,以及是否通过等等。这些信息都需要进行网页截图。

这些信息人事需要进行归档和压缩,如果是人工操作,里面的流程有将近10w+的数据条目。 这如果让人工实现实在是头大,根本无法完成这个巨大的工作量。

自然这种事情落到了我的头上,谁让我们会搞程序呢,呵呵。 我采用的Python3+Selenium的方式,模拟登录比较麻烦需要验证码各种,我直接使用人事账号的登录cookie即可实现登录,那接下来就是访问页面就可以。 访问到对应页面进行截图保存,然后又继续翻页,继续截图,以此类推。

脑海里就浮现了我的实现逻辑。说干就干。

二、Chrome无头浏览器+驱动下载安装

注意事项: google-chrome-stable和chromedriver最好保持一致的版本,否则可能会出现兼容性报错的情况!!!!

1、google-chrome-stable下载安装

bash 复制代码
#1、安装google-chrome-stable的依赖
yum install -y atk at-spi2-atk libdrm mesa-libgbm gtk3 vulkan xdg-utils
#安装中文字体
yum install -y wqy-microhei-fonts

#2、下载rpm安装包
https://mirrors.aliyun.com/google-chrome/google-chrome/google-chrome-stable-110.0.5481.77-1.x86_64.rpm

#3、安装

rpm -ivh google-chrome-stable-110.0.5481.77-1.x86_64.rpm

#4、查看版本信息
google-chrome-stable --version

显示版本信息如下,表示google-chrome-stable安装成功:

2、安装chromedriver驱动

bash 复制代码
# 下载安装包
wget "https://registry.npmmirror.com/-/binary/chromedriver/110.0.5481.77/chromedriver_linux64.zip"

# 解压
unzip chromedriver_linux64.zip -d /usr/local/chromedriver

# 设置环境变量

export CHROME_DRIVER=/usr/local/chromedriver
export PATH=$PATH:$CHROME_DRIVER

# 验证chromedriver版本是否与google-chrome-stable版本完全一致,否则会出现兼容性问题
chromedriver --version

三、Python样例代码

1、pip3安装依赖

bash 复制代码
pip3 install selenium

pip3 install pillow

2、样例代码

访问https://qq.com 腾讯门户网站,将腾讯网截图保存下来。 如果是自己的业务,那么传递cookie这些参考文档传递即可。此时,您就当你的程序就是一个chorme浏览器,chrome浏览器能做的事情,你的代码就能做。 只是平时我们使用chrome是鼠标点点点,换到代码就是调用API函数即可。

python 复制代码
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
import time
import os.path
from PIL import Image

def mergeImage(output_path):
    images = [Image.open(os.path.join(output_path, f"screenshot_{i}.png")) for i in range(scrolls)]
    widths, heights = zip(*(i.size for i in images))

    total_width = max(widths)
    total_height = sum(heights)

    new_image = Image.new('RGB', (total_width, total_height))
    y_offset = 0
    for img in images:
        new_image.paste(img, (0, y_offset))
        y_offset += img.height

    final_screenshot_path = os.path.join(output_path, "final_screenshot.png")
    new_image.save(final_screenshot_path)
    print(f"Final screenshot saved to {final_screenshot_path}")


if __name__ == "__main__":
    # 设置浏览器
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-gpu')
    options.add_argument('--headless')  # 无头参数

    output_path = "./screenshots"
    # 启动浏览器
    driver = Chrome(options=options)
    driver.maximize_window()
    try:
        # 访问页面
        url = 'https://qq.com'
        driver.get(url)
        time.sleep(1)
        # 设置截屏整个网页的宽度以及高度
        scroll_width = 2500
        scroll_height = 9500
        driver.set_window_size(scroll_width, scroll_height)

        # 获取页面高度
        total_height = driver.execute_script("return document.body.scrollHeight")
        viewport_height = driver.execute_script("return window.innerHeight")
        scrolls = int(total_height / viewport_height) + 1

        # 创建输出目录
        if not os.path.exists(output_path):
            os.makedirs(output_path)

        # 滚动并截屏
        for i in range(scrolls):
            y_offset = i * viewport_height
            driver.execute_script(f"window.scrollTo(0, {y_offset});")
            time.sleep(1)  # 等待内容加载
            screenshot_path = os.path.join(output_path, f"screenshot_{i}.png")
            driver.get_screenshot_as_file(screenshot_path)
            print(f"Saved {screenshot_path}")

        # 合并图片
        mergeImage(output_path)

        # 关闭浏览器
        driver.close()
        driver.quit()

    except Exception as e:
        print(e)

3、成功保存截图

四、总结

使用Python的原因是,Python针对爬虫这块包很多,也很擅长, 脚本简单清晰。倒是也没必要上Go、Java之类的,Python处理这类问题信手拈来,效率高才是王道!

Selenium就是个自动化测试框架,底层还可以切换控制Chrome、火狐等等相关浏览器驱动。

相关推荐
B站计算机毕业设计之家20 小时前
大数据毕业设计:基于python图书数据分析可视化系统 书籍大屏 爬虫 清洗 可视化 当当网书籍数据分析 Django框架 图书推荐 大数据
大数据·爬虫·python·机器学习·自然语言处理·数据分析·课程设计
QT 小鲜肉1 天前
【Linux命令大全】003.文档编辑之csplit命令(实操篇)
linux·运维·服务器·chrome·mysql
想看一次满天星1 天前
某里231——AST解混淆流程
爬虫·python·ast·js·解混淆
QT 小鲜肉1 天前
【Linux命令大全】002.文件传输之lpr命令(实操篇)
linux·运维·服务器·网络·chrome·笔记
QT 小鲜肉1 天前
【Linux命令大全】003.文档编辑之comm命令(实操篇)
linux·运维·服务器·javascript·chrome·笔记
QT 小鲜肉1 天前
【Linux命令大全】002.文件传输之lpd命令(实操篇)
linux·运维·服务器·网络·chrome·笔记
Wpa.wk1 天前
接口测试-多层嵌套响应处理-JSONPath使用(Java版)
java·前端·经验分享·python·测试工具·jsonpath
QT 小鲜肉1 天前
【Linux命令大全】003.文档编辑之ed命令(实操篇)
linux·运维·服务器·chrome·github
QT 小鲜肉1 天前
【Linux命令大全】003.文档编辑之col命令(实操篇)
linux·运维·服务器·前端·chrome
yenggd1 天前
wireshark常规用法
测试工具·wireshark·php