是否可以为使用python selenium拍摄的屏幕截图添加文字?

时间:2017-08-04 05:48:44

标签: python selenium webdriver

使用pythonselenium,是否可以在屏幕截图中添加文字?我看到如果在java中执行操作可以完成此操作,但如果使用python则没有看到任何内容。

2 个答案:

答案 0 :(得分:0)

使用PIL图像模块读取PIL图像模块文档Here

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

img = Image.open("screen.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("clear_san.ttf", 23)
sample_text="hello world!"
draw.text((100, 100),sample_text,(28,28,28),font=font)
#here (100,100) is the x,y location of the text and (28,28,28) is the color 
#of font which is drawn on canvas
img.save("final.png")#saving the image
#see the image attached

enter image description here

答案 1 :(得分:0)

你可以使用python selenium和一些(嵌入式)javascript做这样的事情:

from selenium import webdriver

def main():

    URL = 'https://www.google.com'
    SAVE_PATH = '/path/to/screenshots/screenshot.png'
    browser = webdriver.Firefox()
    browser.get(URL)
    browser.execute_script(script())
    browser.save_screenshot(SAVE_PATH)

def script():

    return 'myCanvas = document.createElement("canvas");'\
    + 'myCanvas.id = "myCanvas";'\
    + 'myCanvas.width = document.body.clientWidth;'\
    + 'myCanvas.height = 60;'\
    + 'document.body.insertBefore(myCanvas, document.body.firstChild);'\
    + 'var ctx = myCanvas.getContext("2d");'\
    + 'ctx.font = "50px Monospace";'\
    + 'displayedText = "Hello World!";'\
    + 'ctx.strokeText(displayedText, document.body.clientWidth/2 - 150, 50);'

if __name__ == "__main__":
    main()

但请注意,它不适用于每个站点,并且根据displayedText的值,您必须调整myCanvas.height和ctx.strokeText参数的硬编码值才能使其正确。