Python、Selenium:如何截取PDF全页截图?

问题描述 投票:0回答:1

目前,我看到可以使用 Selenium 创建屏幕截图。但是,它们始终是 .png 文件。我怎样才能截取相同样式的屏幕截图,但作为 .pdf 格式?

要求样式:无边距;与当前页面相同的尺寸(如整页截图)
由于打印附带的所有格式,打印页面无法完成此操作。

我目前如何获取屏幕截图:

from selenium import webdriver

# Function to find page size
S = lambda X: driver.execute_script('return document.body.parentNode.scroll'+X)

driver = webdriver.Firefox(options=options)
driver.get('https://www.google.com')

# Screen 
height = S('Height')
width = S('Width')

driver.set_window_size(width, height)
driver.get_screenshot_as_file(PNG_SAVEAS)

driver.close()
python selenium-webdriver geckodriver
1个回答
0
投票

回答我自己的问题,因为我在任何地方都找不到这些信息,但能够达到预期的结果。

技巧似乎是动态配置 PDF 页面的宽度和高度以匹配正在打印的内容。
更进一步,我将结果缩小到原始大小的 1%(用于优化)。这大大加快了速度。

唯一的另一件事是,如果使用 GeckoDriver,我发现 一个错误 导致生成的 PDF 以错误的尺寸打印。似乎将大小乘以

2.5352112676056335
可以解决这个问题。但是,我一生都无法理解的是为什么。在我的例子中,
2.5352112676056335
对于高度和宽度都是一个常数,但未能利用此修复实际上会导致 PDF 比率完全改变(与仅按比例缩小相反)。这很奇怪。

这是用 GeckoDriver 测试的,我怀疑如果使用 Chrome,则需要删除

RATIO_MULTIPLIER
解决方法。

from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions
import base64

# Bug in geckodriver... seems unrelated, but this wont work otherwise.
# https://github.com/SeleniumHQ/selenium/issues/12066
RATIO_MULTIPLIER = 2.5352112676056335

# Function to find page size
S = lambda X: driver.execute_script('return document.body.parentNode.scroll'+X)

# Scale for PDF size. 1 for no change takes long time
pdf_scaler = .01

# Browser options. Headless is more reliable for screenshots in my exp.
options = webdriver.FirefoxOptions()
options.add_argument('--headless')

# Lanuch webdriver, navigate to destination
driver = webdriver.Firefox(options=options)
driver.get('https://www.google.com')

# Find full page dimensions regardless of scroll
height = S('Height')
weight = S('Width')

# Dynamic setting of PDF page dimensions
print_options = PrintOptions()
print_options.page_height = (height*pdf_scaler)*RATIO_MULTIPLIER
print_options.page_width = (weight*pdf_scaler)*RATIO_MULTIPLIER
print_options.shrink_to_fit = True

# Prints to PDF (returns base64 encoded data. Must save)
pdf = driver.print_page(print_options=print_options)
driver.close()

# save the output to a file.
with open('example.pdf', 'wb') as file:
    file.write(base64.b64decode(pdf))

壁虎驱动程序 0.31.0
火狐 113.0.1
硒==4.9.1
Python 3.11.2
视窗 10

© www.soinside.com 2019 - 2024. All rights reserved.