How can I take screenshot of only relevant content of any webpage using Selenium and Python?
Currently I'm taking screenshot of the whole page. Also I want avoid referencing any class or id while taking the screenshot. Please let me know if I can achieve this (if yes, HOW?) or have to change my requirements. If there is any workaround such as cropping the relevant content, please do share too. Thanks.
CodePudding user response:
Chrome appears to be a bit temperamental when screenshotting - only takes what's visible on screen, so I would advise Firefox/geckodriver for these kind of jobs. The following will take a full screenshot of that element:
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options as Firefox_Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
import time as t
firefox_options = Firefox_Options()
firefox_options.add_argument("--width=1280")
firefox_options.add_argument("--height=720")
# firefox_options.headless = True
driverService = Service('chromedriver/geckodriver')
browser = webdriver.Firefox(service=driverService, options=firefox_options)
actions = ActionChains(browser)
url = 'https://www.startech.com.bd/benq-gw2480-fhd-monitor'
browser.get(url)
elem = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//section[@id='specification']")))
elem.screenshot('fullspec.png')
print('screenshotted specs')