A B
A B

Reputation: 107

Selenium how to capture element screenshot?

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?

Upvotes: 0

Views: 1121

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193088

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
    

Upvotes: 1

Mayanglambam Yaiphaba
Mayanglambam Yaiphaba

Reputation: 61

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.

Upvotes: 0

Related Questions