Python Selenium 调用网页打印机另存 PDF

之前写过一篇文章(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,
### 使用 Python Selenium网页导出为 PDF 为了实现这一目标,可以利用 Chrome 浏览器的打印功能来将页面内容保存成 PDF 文件。下面展示了具体的方法: #### 方法一:通过设置 Chrome 打印选项 可以通过配置 `PrintOptions` 来指定输出格式为 PDF 并调整其他参数。 ```python from selenium import webdriver from selenium.webdriver.chrome.options import Options as ChromeOptions from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.print_page_options import PrintPageOptions def save_webpage_as_pdf(url, output_path): chrome_service = Service('chromedriver') # 假设 chromedriver 和脚本在同一目录下 options = ChromeOptions() prefs = { "download.default_directory": "/tmp", # 设置默认下载路径 "plugins.always_open_pdf_externally": True, "printing.print_preview_sticky_settings.appState": "{\"recentDestinations\":[{\"id\":\"Save as PDF\",\"origin\":\"local\",\"account\":\"\"]}" } options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(service=chrome_service, options=options) try: driver.get(url) print_options = PrintPageOptions() print_options.orientation = 'portrait' print_options.scale = 1 pdf_content_base64 = driver.print_page(print_options=print_options) with open(output_path, 'wb') as f: f.write(base64.b64decode(pdf_content_base64)) finally: driver.quit() save_webpage_as_pdf('http://example.com', './output.pdf') ``` 这段代码定义了一个函数 `save_webpage_as_pdf()` 接受两个参数——URL 地址以及期望存储 PDF 的本地文件位置[^1]。 #### 方法二:模拟点击浏览器菜单操作 另一种方式则是模仿用户行为,在打开的目标网站上触发“另存PDF”的动作。这种方式依赖于特定浏览器的行为模式,可能不如前一种稳定可靠。 ```python import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains driver = webdriver.Chrome(service=Service('/path/to/chromedriver')) try: url = 'https://www.example.com/' driver.get(url) actions = ActionChains(driver) body_element = driver.find_element_by_tag_name('body') # Ctrl + P 模拟键盘快捷键组合用于调起打印对话框 actions.key_down(Keys.CONTROL).send_keys('p').key_up(Keys.CONTROL).perform() time.sleep(2) # 等待弹窗出现 # 这里假设已经选择了"保存为PDF" # 需要额外编写逻辑去确认并提交表单 finally: driver.close() ``` 需要注意的是上述例子仅适用于某些场景下的简单应用;对于复杂情况建议采用第一种方法[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值