Home > Back-end >  Selenium how to capture element screenshot?
Selenium how to capture element screenshot?

Time:12-06

I am trying to access the "canvas" element, sin the screenshot.

I am running the following code:

driver.find_element_by_tag_name('canvas').screenshot("canvas.png")
driver.find_element_by_tag_name('canvas').screenshot_as_png("chess.png")

enter image description here

Neither of the 2 above work, what am I missing?

CodePudding user response:

You were close enough. The <canvas> tag is within the <chess-board> tag.


Solution

Ideally you need to induce WebDriverWait for the visibility_of_element_located() for the <canvas> element and you can use either of the following locator strategies:

  • Using TAG_NAME:

    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.TAG_NAME, "canvas"))).screenshot_as_png("chess.png")
    
  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "chess-board > canvas"))).screenshot_as_png("chess.png")
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//chess-board/canvas"))).screenshot_as_png("chess.png")
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

CodePudding user response:

1)Create a class. Implement TestNG 'ITestListener'. 2)Call the method 'onTestFailure'. 3)Add the code to take a screenshot with this method. 4)Get the Test method name and take a screenshot with the test name. Then place it in the desired destination folder.

  • Related