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

相关推荐
喵手4 小时前
Python爬虫实战:针对天文历法网站(以 TimeandDate 或类似的静态历法页为例),构建高精度二十四节气天文数据采集器(附xlsx导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集天文历法网站数据·构建二十四节气天文数据
喵手6 小时前
Python爬虫实战:采集博客园 Cnblogs文章标题、发布日期、标签以及HTML正文等(附 Markdown 文档格式预览)!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·博客园文章采集·博客园文章采集转md格式
10岁的博客6 小时前
Libvio.link爬虫技术全解析
爬虫
深圳博众测控6 小时前
博众测控 | ISO 16750-2:2023汽车电气测试新标准解读:关键变化与测试设备选型
人工智能·测试工具·汽车
ziqi5228 小时前
第二十五天笔记
前端·chrome·笔记
2501_948120159 小时前
大语言模型与爬虫技术融合的智能数据采集系统
人工智能·爬虫·语言模型
喵手10 小时前
Python爬虫实战:采集巨潮资讯网等上市公司公告数据,通过智能关键词匹配技术识别分红、回购、停牌等重要信息(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集巨潮资讯数据·智能匹配识别分红、回购等信息·csv导出+sqlite
hvang198810 小时前
某花顺隐藏了重仓涨幅,通过chrome插件计算基金的重仓涨幅
前端·javascript·chrome
泡泡以安10 小时前
Android 逆向实战:从零突破某电商 App 登录接口全参数加密
android·爬虫·安卓逆向
axinawang11 小时前
第9章 存储爬虫数据
爬虫