有什么方法可以调用 chromedriver 的 Page.printToPDF()来自python + selenium的方法?
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,但这对存储来说很麻烦目的)。
最佳答案
可以通过调用 Page.printToPDF
来实现来自 DevTool API。但是,此命令是实验性的,并未在所有平台上实现:
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 })
关于python - Selenium + ChromeDriver printToPDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023842/