之前写过一篇文章(Python Selenium 网页长截图/HTML 转 PDF)网页截图转PDF,但以图片形式保存的pdf在阅读时不太友好。网上搜索文章时,发现可以直接调用网页打印机另存为PDF,下面为核心代码,测试浏览器Chrome。
import time,json
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
path = r'C:\Users\XXXX\Desktop' # 修改为网页转PDF后要保存的路径
#%% chrome 选项,调用浏览器打印机,另存为pdf
chrome_options = webdriver.ChromeOptions()
settings = {"recentDestinations": [{"id": "Save as PDF",
"origin": "local",
"account": ""
}],
"selectedDestinationId": "Save as PDF",
"version": 2,