利用chromedriver,保存html为pdf文件
你可以利用Selenium和ChromeDriver来生成PDF文件。为了实现这个,你需要使用Chrome的Headless模式以及Chrome DevTools Protocol中的Page.printToPDF
功能。
以下是一个Python示例,它会把一个网页保存为PDF:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import time, json
options = Options()
# Enable headless mode
options.add_argument("--headless")
# Set path to chromedriver as per your configuration
webdriver_service = Service('path/to/chromedriver')
driver = webdriver.Chrome(service=webdriver_service, options=options)
# Go to the page you want
driver.get('http://www.google.com')
time.sleep(2) # might need a pause if the site is slow
# Enable the Chrome Devtools Protocol
driver.execute_cdp_cmd("Page.enable", {})
# Configure the Page to print to PDF
params = {
'landscape': False,
'displayHeaderFooter': False,
'printBackground': True,
'preferCSSPageSize': True,
}
# Get the PDF data
pdf = driver.execute_cdp_cmd("Page.printToPDF", params)
# Save the PDF file
with open('output.pdf', 'wb') as output_file:
output_file.write(base64.b64decode(pdf['data']))
driver.quit()
请注意,此脚本在运行时需要Python环境,并已安装selenium库。你也需要根据你的实际需要调整一些参数,例如chromedriver的路径,要转换为PDF的网页URL,以及PDF文件的存储位置。