【问题标题】:Selenium + ChromeDriver printToPDFSelenium + ChromeDriver printToPDF
【发布时间】:2018-04-11 22:33:22
【问题描述】:

有没有办法从 python + selenium 调用 chromedriver 的 Page.printToPDF() 方法?

PhantomJS 有一个类似的render() 方法,可以直接保存为 pdf,该方法只能从 phantomjs 的特权客户端 REPL 中获得。 This SO answer 展示了如何修补正在运行的 selenium 驱动程序以调用它,使用自定义 phantomjs webdriver 命令 (/session/$sessionId/phantom/execute) 调用 this.render()

chromedriver 可以做类似的事情吗?像 phantomjs 的 execute 命令允许调用 devtools 方法;还是通过自定义驱动程序命令直接调用printToPDF

(注意:我正在尝试渲染作为 POST 的结果的 html,因此 wkhtmltopdf 之类的替代解决方案将不起作用。我可以回退到使用 selenium 的屏幕截图 -> png,但这对于存储来说很麻烦目的).

【问题讨论】:

    标签: python selenium selenium-chromedriver


    【解决方案1】:

    可以通过从 DevTool API 调用 Page.printToPDF 来实现。然而,这个命令是实验性的,并没有在所有平台上实现:

    from selenium import webdriver
    import json, base64
    
    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)
      if response['status']:
        raise Exception(response.get('value'))
      return response.get('value')
    
    def save_as_pdf(driver, path, options={}):    
      # https://timvdlippe.github.io/devtools-protocol/tot/Page#method-printToPDF
      result = send_devtools(driver, "Page.printToPDF", options)
      with open(path, 'wb') as file:
        file.write(base64.b64decode(result['data']))
    
    
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")
    options.add_argument("--disable-gpu")
    
    driver = webdriver.Chrome(chrome_options=options)
    driver.get("https://www.google.co.uk/")
    
    save_as_pdf(driver, r'page.pdf', { 'landscape': False })
    

    【讨论】:

    • 谢谢,正是我想要的!虽然我收到了PrintToPDF is not implemented 错误回复。我需要做些什么来启用实验性功能吗? (Selenium 报告它正在连接到 Chrome 62.0.3202.62、ChromeDriver 2.32、Platform=Linux)。据我所知,该版本应该(?)支持 printToPDF。
    • 尝试使用金丝雀版本或woolyss (64.0.3249.0) 的最新版本
    • 啊,查到了。根据puppeteer's printToPDF docs,它目前仅在无头模式下可用。我一打开它,一切就完美了。
    【解决方案2】:

    好的,仅供参考,这就是我在 2019 年如何让它工作而不产生异常:

    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)
        #print (response)
        if (response.get('value') is not None):
            return response.get('value')
        else:
            return None
    
    def save_as_pdf(driver, path, options={}):
        # https://timvdlippe.github.io/devtools-protocol/tot/Page#method-printToPDF
        result = send_devtools(driver, "Page.printToPDF", options)
        if (result is not None):
            with open(path, 'wb') as file:
                file.write(base64.b64decode(result['data']))
            return True
        else:
            return False
    

    【讨论】:

    猜你喜欢
    • 2017-02-09
    • 2020-06-22
    • 2015-04-12
    • 2020-08-16
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2013-07-26
    相关资源
    最近更新 更多