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

相关推荐
Amazon数据采集19 分钟前
🚀 Pangolin Scrape API实战指南:从0到1构建高性能亚马逊数据采集系统
爬虫·自动化运维
zhonghaoxincekj1 小时前
晶体管的定义,晶体管测量参数和参数测量仪器
功能测试·单片机·学习·测试工具·单元测试·制造
dyxal2 小时前
VS Code 1.52.1 对应一些插件版本
前端·chrome
乌萨奇也要立志学C++6 小时前
【Linux】基础IO(一)Linux 文件操作从入门到实践:系统调用、文件描述符、重定向,为自定义Shell添加重定向
linux·运维·chrome
DataLaboratory9 小时前
Python爬取百度地图-前端直接获取
爬虫·python·百度地图
Turnsole_y12 小时前
pycharm自动化测试初始化
python·selenium
技术钱14 小时前
uniapp使用音频录音功能
chrome·uni-app·音视频
oh,huoyuyan17 小时前
如何在火语言中指定启动 Chrome 特定用户配置文件
前端·javascript·chrome
APIshop18 小时前
代码实例:Python 爬虫抓取与解析 JSON 数据
爬虫·python·json
川石课堂软件测试19 小时前
自动化测试之 Cucumber 工具
数据库·功能测试·网络协议·测试工具·mysql·单元测试·prometheus