1.截取长图
注:selenium 必须开启无界面模式
from selenium import webdriver import time options = webdriver.ChromeOptions() options.add_argument('--disable-gpu') # 禁用gpu options.add_argument('--ignore-certificate-errors') #忽略一些莫名的问题 options.add_experimental_option('excludeSwitches', ['enable-automation']) # 开启开发者模式 options.add_argument('--disable-blink-features=AutomationControlled') # 谷歌88版以上防止被检测 options.add_argument('--headless') # 无界面 driver = webdriver.Chrome(options=options) # 将chromedriver放到Python安装目录Scripts文件夹下 url = f"file://D:/font/html/1.html" driver.get(url) time.sleep(1) js_height = "return document.body.clientHeight" k = 1 height = driver.execute_script(js_height) while True: if k * 500 < height: js_move = "window.scrollTo(0,{})".format(k * 500) driver.execute_script(js_move) time.sleep(0.2) height = driver.execute_script(js_height) k += 1 else: break # 注:必须开启无界面模式,即:--headless # 接下来是全屏的关键,用js获取页面的宽高,如果有其他需要用js的部分也可以用这个方法 width = driver.execute_script("return document.body.scrollWidth") height = driver.execute_script("return document.body.scrollHeight") # 将浏览器的宽高设置成刚刚获取的宽高 driver.set_window_size(width, height) time.sleep(1) # 截图并关掉浏览器 png_file = f'D:/font/png/1.png' driver.save_screenshot(png_file) time.sleep(0.5) driver.close()
2. 设置截图页面大小
from selenium import webdriver import time options = webdriver.ChromeOptions() options.add_argument('--disable-gpu') # 禁用gpu options.add_argument('--ignore-certificate-errors') #忽略一些莫名的问题 options.add_experimental_option('excludeSwitches', ['enable-automation']) # 开启开发者模式 options.add_argument('--disable-blink-features=AutomationControlled') # 谷歌88版以上防止被检测 options.add_argument('--headless') # 无界面 driver = webdriver.Chrome(options=options) # 将chromedriver放到Python安装目录Scripts文件夹下 driver.set_window_size(2200, 1200) # 设置页面大小 url = f"file://D:/font/html/1.html" driver.get(url) time.sleep(1) png_file = f'D:/2/{1}.png' driver.save_screenshot(png_file) driver.close()