How to take a screenshot of a web element and compare its text content?

1k Views Asked by At

I want to capture a screenshot of a specific web element using Selenium WebDriver and compare its text content with the existing text data. So, how can I access the text content of the screenshot once it has been captured? And, I would like to use either an XPath or any other selector method as the element does not have an ID. Thank you.

1

There are 1 best solutions below

0
Ajeet Verma On

We can take a screenshot of the WebElement

We can take a screenshot of the WebElement (an img tag in the given example) which is a captcha and to read the text on the taken screenshot, we can use the library ddddocr.

Here is the solution,

from selenium import webdriver
from selenium.webdriver.common.by import By

import ddddocr

driver = webdriver.Chrome()

driver.get('https://ma.mohw.gov.tw/masearch/')

captcha = driver.find_element(By.ID, "ctl00_ContentPlaceHolder1_ImageCheck")
captcha.screenshot(f'captcha.png')

ocr = ddddocr.DdddOcr()
# open and read the image
with open(f'captcha.png', 'rb') as f:
    img_bytes = f.read()

res = ocr.classification(img_bytes)
print(res.upper())
>> PUT7