我试图将网页导出为带有Google chrome和硒的PDF文件。当我在代码中提交chrome_options.add_argument('--headless')
行时,它运行得很好,但是在无头模式下不起作用。输出文件,无错误/警告。
我试图导出的网页包含延迟加载图像,所以我写了一个javascript将其滚动到底部,因此不能直接使用--print-to-pdf。 Google Chrome版本75.0.3770.142(正式版本)(64位) 驱动程序版本75.0.3770.140
from selenium import webdriver
from selenium.webdriver import ChromeOptions as Options
import json
import time
chrome_options = Options()
appState = {
"recentDestinations": [
{
"id": "Save as PDF",
"origin": "local"
}
],
"selectedDestinationId": "Save as PDF",
"version": 2
}
profile = {
'printing.print_preview_sticky_settings.appState': json.dumps(appState),
'savefile.default_directory': './'
}
chrome_options.add_experimental_option('prefs', profile)
# chrome_options.add_argument('--headless')
chrome_options.add_argument('--kiosk-printing')
chrome_options.add_argument('--incognito')
chrome_driver = webdriver.Chrome('/home/ar8327/PycharmProjects/lazyload_spider/chromedriver',chrome_options=chrome_options)
chrome_driver.implicitly_wait(60)
chrome_driver.get('https://mp.weixin.qq.com/s/MY0AeHpvEoayLVc46EQjfw')
time.sleep(1)
chrome_driver.execute_script('function sleep(ms){return new Promise((resolve)=>setTimeout(resolve,ms));}var currentPosition2, timer2;async function GoBottom() {currentPosition2 = document.documentElement.scrollTop;while(currentPosition2<=document.body.scrollHeight){currentPosition2 += 50;window.scrollTo(0,currentPosition2);var temple=await sleep(100);}return 0;}GoBottom();')
time.sleep(40)
chrome_driver.execute_script('window.print();')
chrome_driver.quit()
我希望代码在启用无头模式时能工作