0

Using python and selenium, is it possible to add text to the screenshot? I saw that this could be done if doing things in java, but didn't see anything if using python.

Rahul
  • 10,830
  • 4
  • 53
  • 88
user655489
  • 1,316
  • 3
  • 14
  • 21
  • This deserves answer though :) – Nabin Aug 04 '17 at 05:54
  • 5
    Once you create your image with selenium, then you can use PIL. `import PIL` and add your text using the following link. [writing text on image using pil](https://stackoverflow.com/questions/8154825/how-can-i-write-text-over-an-image-and-overlay-another-image-on-it-in-python) – Hara Aug 04 '17 at 05:55

2 Answers2

2

Use PIL image module read PIL image module documentation 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

mayure098
  • 111
  • 1
  • 5
0

You can do something like this, using python selenium and a bit of (embedded) 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()

Note however that it does not work well for every site and depending on the value of displayedText, you have to tweak the hardcoded values of myCanvas.height and ctx.strokeText parameters to get it right.

elias-pap
  • 1
  • 1