Python使用selenium chrome无头模式html转换为pdf,亲测linux可运行

完整代码 Page.printToPDF

说明: 我这里用的是Python3.12.3, selenium4.0版本

import base64
import json
import os
import time

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service


def send_devtools(driver, cmd, params={}):
    resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
    url = driver.command_executor._url + resource
    body = json.dumps({'cmd': cmd, 'params': params})
    response = driver.command_executor._request('POST', url, body)
    return response.get('value')


def save_as_pdf(driver, path, options={}):
    result = send_devtools(driver, "Page.printToPDF", options)
    with open(path, 'wb') as file:
        file.write(base64.b64decode(result['data']))


if __name__ == "__main__":
    # Chrome浏览器以及chromedriver的存放文件夹,注意chrome浏览器和chromedriver的版本号要保持同一个版本,不然会报版本错误
    chrome_location = os.path.join(os.getcwd(), 'chrome-win')
    # Chrome浏览器的位置
    browser_location = os.path.join(chrome_location, 'chrome.exe')
    # ChromeDriver的位置
    driver_location = os.path.join(chrome_location, 'chromedriver.exe')

    # linux上 chrome和chromedriver
    #chrome_location = os.path.join(current_path, 'chrome-linux')
    #browser_location = os.path.join(chrome_location, 'chrome')
    #driver_location = os.path.join(chrome_location, 'chromedriver')
    #print('Linux上ChromeDriver的位置:', driver_location)



    # 创建一个Servic对象,传入ChromeDriver的路径
    service = Service(driver_location)
    # 创建Chrome选项
    options = Options()
    # 无头模式,无界面
    options.add_argument("--headless")
    options.add_argument("--disable-gpu")

    driver = webdriver.Chrome(options, service)
    try:
        driver.get("https://www.baidu.com")
        time.sleep(3)  # 如果页面复杂,非静态页面,建议适当给延迟,等待页面彻底加载完成
        # 创建存放pdf文件夹
        prefix_path = os.path.join(os.getcwd(), 'pdf')
        if not os.path.exists(prefix_path):
            os.makedirs(prefix_path)
        # 完成的pdf的完整路径,可以根据自己的需求自己设置文件路径、文件名
        save_path = os.path.join(prefix_path, 'my.pdf')
        print(save_path)
        # landscape 布局: true:横向,false:纵向,默认值
        # pageRanges 页面 默认空,代表打印全部,也可以打印部分也例如: '1-5'
        # printBackground 打印背景, true:打印背景,false: 不打印背景 默认是false
        save_as_pdf(driver, save_path,
                    {'landscape': True, 'pageRanges': '', 'printBackground': True})
    except Exception as e:
        print(e)
    finally:
        driver.quit()

亲测Linux环境可运行

因为需要部署linxu环境,安装完Python环境和chrome浏览器

注意Linux上的chromedriver也要和chrome浏览器版本一致

本人亲测,Linux上selenium chrome浏览器无头模式 ,html转换(打印)为pdf完全可以

参考资料 https://www.cnblogs.com/new-june/p/15347577.html 

               https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF

  • 16
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Python Selenium无头模式,你可以通过设置ChromeOptions来实现。无头模式是指在不显示浏览器界面的情况下运行Selenium脚本,以提高脚本的运行效率和稳定性。 以下是一个示例代码,演示了如何使用PythonSelenium无头模式运行脚本: ```python from selenium import webdriver from selenium.webdriver.chrome.options import Options # 创建ChromeOptions对象 chrome_options = Options() # 设置无头模式 chrome_options.add_argument('--headless') # 创建webdriver对象,并传入ChromeOptions对象 driver = webdriver.Chrome(options=chrome_options) # 在无头模式运行脚本 driver.get('https://www.example.com') # 其他操作... # 关闭webdriver driver.quit() ``` 在上述代码中,通过创建ChromeOptions对象,并使用`add_argument`方法传入`--headless`参数,实现了无头模式。然后将ChromeOptions对象传入webdriver的options参数中,即可在无头模式运行脚本。 希望以上信息对你有所帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python_Selenium使用](https://blog.csdn.net/weixin_42160053/article/details/124960614)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Pythonselenium的玩法,小朋友看了都说学会了](https://blog.csdn.net/AI19970205/article/details/120048773)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值