提示信息

利用chromedriver,保存html为pdf文件

心灵家园 已关注

你可以利用Selenium和ChromeDriver来生成PDF文件。为了实现这个,你需要使用Chrome的Headless模式以及Chrome DevTools Protocol中的Page.printToPDF功能。

以下是一个Python示例,它会把一个网页保存为PDF:

  1. from selenium import webdriver
  2. from selenium.webdriver.chrome.service import Service
  3. from selenium.webdriver.common.by import By
  4. from selenium.webdriver.chrome.options import Options
  5. from selenium.webdriver.common.action_chains import ActionChains
  6. from selenium.webdriver.common.keys import Keys
  7. from selenium.webdriver.support.ui import Select
  8. import time, json
  9. options = Options()
  10. # Enable headless mode
  11. options.add_argument("--headless")
  12. # Set path to chromedriver as per your configuration
  13. webdriver_service = Service('path/to/chromedriver')
  14. driver = webdriver.Chrome(service=webdriver_service, options=options)
  15. # Go to the page you want
  16. driver.get('http://www.google.com')
  17. time.sleep(2) # might need a pause if the site is slow
  18. # Enable the Chrome Devtools Protocol
  19. driver.execute_cdp_cmd("Page.enable", {})
  20. # Configure the Page to print to PDF
  21. params = {
  22. 'landscape': False,
  23. 'displayHeaderFooter': False,
  24. 'printBackground': True,
  25. 'preferCSSPageSize': True,
  26. }
  27. # Get the PDF data
  28. pdf = driver.execute_cdp_cmd("Page.printToPDF", params)
  29. # Save the PDF file
  30. with open('output.pdf', 'wb') as output_file:
  31. output_file.write(base64.b64decode(pdf['data']))
  32. driver.quit()

请注意,此脚本在运行时需要Python环境,并已安装selenium库。你也需要根据你的实际需要调整一些参数,例如chromedriver的路径,要转换为PDF的网页URL,以及PDF文件的存储位置。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
心灵家园 关注 已关注

最近一次登录:2023-09-18 08:49:39   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图