Selenium + Chromedriver Printtopdf
Is there any way to invoke chromedriver's Page.printToPDF() method from python + selenium? PhantomJS has a similar render() method that can save straight to pdf, which is only ava
Solution 1:
It's possible by calling Page.printToPDF
from the DevTool API. However this command is experimental and not implemented on all the platforms:
from selenium import webdriver
import json, base64
defsend_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')
defsave_as_pdf(driver, path, options={}):
# https://timvdlippe.github.io/devtools-protocol/tot/Page#method-printToPDF
result = send_devtools(driver, "Page.printToPDF", options)
withopen(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 })
Solution 2:
OK, only for reference, this is how I made it work on 2019 without generating an exception:
defsend_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') isnotNone):
return response.get('value')
else:
returnNonedefsave_as_pdf(driver, path, options={}):
# https://timvdlippe.github.io/devtools-protocol/tot/Page#method-printToPDF
result = send_devtools(driver, "Page.printToPDF", options)
if (result isnotNone):
withopen(path, 'wb') as file:
file.write(base64.b64decode(result['data']))
returnTrueelse:
returnFalse
Post a Comment for "Selenium + Chromedriver Printtopdf"