You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows正常运行的HTML转PDF Python代码在macOS报错,求修复方案

修复macOS上HTML转PDF代码的语法错误

问题根源

你代码里第26行的f"--window-size=700,{height}"是Python 3.6才引入的f-string语法,如果你的macOS系统默认Python版本低于3.6(比如早期macOS自带的Python 2.7或3.5),就会触发语法无效错误。此外代码还有几个潜在问题需要修正:

  • 缺少selenium.webdriver的导入语句
  • 重复导入from PIL import Image
  • 两次创建Chrome Driver,冗余且低效
  • 固定time.sleep(3)可能导致页面未完全加载

修复步骤

  1. 替换f-string语法:用兼容旧版本Python的方式替代f-string,更推荐直接调用Driver的窗口尺寸设置方法
  2. 补充缺失的导入:添加from selenium import webdriver
  3. 移除重复导入:删掉重复的from PIL import Image
  4. 优化Driver逻辑:复用Driver实例,避免重复启动关闭浏览器
  5. 替换固定等待:改用显式等待替代time.sleep,提升稳定性

修复后的完整代码

from PIL import Image
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
import img2pdf
import os
import sys

arguments = sys.argv
FileUrl = arguments[1]

# 初始化Chrome配置
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--hide-scrollbars")

for path, currentDirectory, files in os.walk(FileUrl):
    for file in files:
        if file.endswith(".html"):
            filepath = os.path.join(path, file)
            imageoutputPath = filepath.replace('.html','_desktop.png')
            pdfoutputPath = filepath.replace('.html','_desktop.pdf')
            
            # 启动一次Driver复用
            driver = webdriver.Chrome(options=chrome_options)
            driver.get(filepath)
            
            # 显式等待页面加载完成(等待body元素加载)
            WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
            
            # 获取页面高度
            height = driver.execute_script("""
                return Math.max(
                    document.body.scrollHeight, 
                    document.body.offsetHeight, 
                    document.documentElement.clientHeight, 
                    document.documentElement.scrollHeight, 
                    document.documentElement.offsetHeight
                )
            """)
            print(f"页面高度: {height}")
            
            # 直接设置窗口尺寸,替代命令行参数方式
            driver.set_window_size(700, height)
            # 等待尺寸生效
            time.sleep(0.5)
            
            # 截图
            driver.save_screenshot(imageoutputPath)
            
            # 转PDF,用with语句自动管理文件
            image = Image.open(imageoutputPath)
            pdf_bytes = img2pdf.convert(image.filename)
            with open(pdfoutputPath, "wb") as pdf_file:
                pdf_file.write(pdf_bytes)
            
            # 清理资源
            image.close()
            os.remove(imageoutputPath)
            driver.quit()
            
            print(f"PDF生成成功: {pdfoutputPath}")

关键修改说明

  • 用driver.set_window_size(700, height)替代命令行参数:直接调用Driver API更可靠,同时兼容所有Python版本
  • 引入显式等待:确保页面完全加载后再获取高度,避免因页面加载慢导致的高度计算错误
  • 复用Driver实例:减少浏览器启动关闭的开销,提升批量处理效率
  • 用with语句管理文件:避免手动关闭文件时可能出现的资源泄漏

内容的提问来源于stack exchange,提问作者Topdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:30:47