pythonseleniumhelium

Take screenshot using helium in python


I am trying to take a snapshot of a specific element within the page using helium in python and here's my code

from selenium.webdriver.chrome.options import Options
from helium import *

url = 'exampleurl'
options = Options()
options.binary_location = "C:/Program Files/Google/Chrome/Application/chrome.exe"

browser = start_chrome(url, headless=False, options=options)
#.FindElementById("viewPane").ScrollIntoView True
element = browser.find_element_by_xpath("//*[@id='frmCaseNo']/div[2]/img")
#element.get_screenshot_as_file("Number.png")
#element.screenshot('Number.png')
#element.save_screenshot('Number.png')
#get_driver().save_screenshot('Number.png')
get_driver().element.save_screenshot('Number.png')

This line succeeds with helium get_driver().save_screenshot('Number.png') but this line doesn't deal with specific element. How can I deal with a specific element and take snapshot of it?


Solution

  • Helium exposes all the selenium methods also , so if you check webelement class

    https://www.selenium.dev/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webelement.html

    you can see there is method called

      webelement.screenshot("hellium.png") 
    

    , which will save the elements screenshot as helium.png

    so in your case use:

    element = browser.find_element_by_xpath("//*[@id='frmCaseNo']/div[2]/img")
    browser.execute_script("arguments[0].scrollIntoView();", element)
    element.screenshot("Number.png") 
    

    element.screenshot("hellium.png")

    full code:

    from helium import *
    from selenium.webdriver.chrome.options import Options
    from shutil import copyfile
    #copying it to current directory so that you don't have to do it
    copyfile(r"C:\Users\Downloads\chromedriver.exe", "chromedriver.exe")
    options=Options()
    
    options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
    browser = start_chrome("https://www.google.com",options=options)
    browser.find_element_by_xpath("//body").screenshot("test.png")