Centos环境下Selenium保存长截图

链接:

怎么把HTML的报告转换为图片,利用无头浏览器:https://www.cnblogs.com/MasterMonkIntemple/p/10558090.html

下面的脚本做了linux和window的兼容性测试:

在windows、linux运行此python脚本都要提前安装selenium(通过pip install),chrome,chromedriver,无需装Xvfb

# -*- coding: utf-8 -*-
from selenium import webdriver
from datetime import datetime
html_location = ''
save_file_full_path = ''
import platform
if platform.system().lower() == 'windows':
    html_location = "file:///D:/tmp/day_report.html"
    save_file_full_path = 'D:/tmp/day_report.png'
else:
    html_location = "file:///root/day_report.html"
    save_file_full_path = '/root/day_report.png'

option = webdriver.ChromeOptions()
option.add_argument("--headless")
option.add_argument("start-maximized")
option.add_argument("enable-automation")
option.add_argument("--no-sandbox")
option.add_argument("--disable-infobars")
option.add_argument("--disable-dev-shm-usage")
option.add_argument("--disable-browser-side-navigation")
option.add_argument("--disable-gpu")
#此处的window-size指的是浏览器以什么尺寸展示 option.add_argument(
"--window-size=1920,1080")
#此处的的hide-scrollbars是隐藏浏览器右边的滚动条 option.add_argument(
"--hide-scrollbars") driver = webdriver.Chrome(chrome_options=option) driver.implicitly_wait(60) driver.get(html_location) print(driver.title)
#这里为了截长图需要用js计算html docment长度和宽度有多大 width
= driver.execute_script("return document.documentElement.scrollWidth") height = driver.execute_script("return document.documentElement.scrollHeight") print(f'width:{width},height:{height}') driver.set_window_size(width, height)
#在linux环境下此处的方法会阻塞,一部分概率会timeout异常,如果不捕获再执行此方法,可能图片就没法生成
#最好使用while循环来判断是否timeout,如果timeout继续get_screenshot_as_file
try: driver.get_screenshot_as_file(save_file_full_path) except: driver.get_screenshot_as_file(save_file_full_path) finally: driver.quit() print("========")

遇到的问题:

1、浏览器遇到的本地html转成图片,可以使用file://

2、网页截图中文显示为方框,原因:linux系统中缺少支持的中文字体。
   解决方案:a、下载任意一款中文字体(ttf格式的字体),我选择的是simsun.ttc ,也就是宋体
           b、将该字体文件放入/usr/share/fonts/路径下

3、在linux下,selenium用webdriver启动控制浏览器,实际上是让浏览器运行在一个显示器里显示,如何在linux下模拟显示器?

  方法一:安装Xvfb创建虚拟Xwindow输出,

    方法二:使用浏览器自带的headless模式运行

链接:在无GUI环境下,配置并使用Python+selenium+chromium/firefox:https://www.jianshu.com/p/decad0692340

 

posted @ 2021-01-27 22:44  feibazhf  阅读(539)  评论(0编辑  收藏  举报