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、火狐等等相关浏览器驱动。

相关推荐
奋进的电子工程师19 小时前
新架构下高精度时间戳总线接口卡 TestBase VCI 0620
测试工具·fpga开发·软件工程
java1234_小锋20 小时前
[免费]基于Python的天气预报(天气预测分析)(Django+sklearn机器学习+selenium爬虫)可视化系统【论文+源码+SQL脚本】
爬虫·python·selenium·天气预报·天气预测
38242782720 小时前
python3网络爬虫开发实战 第2版:使用aiohttp
开发语言·爬虫·python
线束线缆组件品替网20 小时前
Aries Electronics 定制线缆选型与设计建议
数码相机·测试工具·智能手机·电脑·pcb工艺
APIshop21 小时前
API 接口文档测试:从“能跑”到“敢上线”的完整闭环
爬虫·python
盼哥PyAI实验室21 小时前
[特殊字符]️ 实战爬虫:Python 抓取【采购公告】接口数据(含踩坑解析)
开发语言·爬虫·python
may_一一21 小时前
selenium自动化调用接口为null问题处理
selenium·测试工具·自动化
38242782721 小时前
python:selenium,CSS位置偏移反爬案例
css·python·selenium
QT 小鲜肉1 天前
【Linux命令大全】001.文件管理之od命令(实操篇)
linux·运维·服务器·chrome·笔记
刃神太酷啦1 天前
Linux 底层核心精讲:环境变量、命令行参数与程序地址空间全解析----《Hello Linux!》(7)
linux·运维·服务器·c语言·c++·chrome·算法