如何拍摄元素的屏幕截图并将其保存为pdf格式?

2024-09-20 23:03:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须拍摄一个元素的截图,并将其保存为pdf格式。现在我只截图,然后保存它,但我仍然不知道如何将它转换成pdf

我如何做到这一点?这是迄今为止的代码:

               #save screenshot 
               sleep(4)
               constancia =  wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/table[2]')))
               constancia_screenshot = constancia.screenshot_as_png

               with open('constancia.png', 'wb') as f:
                   f.write(constancia_screenshot)

Tags: to代码元素pdfpngsaveas格式
2条回答
import io
from PIL import Image
from importlib import reload
import sys
import time
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium import webdriver


driver = webdriver.Chrome()

driver.get("https://www.google.com")


constancia_screenshot = driver.find_element_by_tag_name('body').screenshot_as_png
a = io.BytesIO(constancia_screenshot)

image1 = Image.open(a)
im1 = image1.convert('RGB')
im1.save(r'a.pdf')

如图所示,使用pillow和io模块,pillow将字节转换为文件,然后使用pillow进行转换

https://pypi.org/project/Pillow/

看一下从png到pdf的转换

这里有一个这样的图书馆: https://pypi.org/project/img2pdf/

import img2pdf

# opening from filename
with open("name.pdf","wb") as f:
    f.write(img2pdf.convert('test.jpg'))

相关问题 更多 >

    热门问题