from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options
from PIL import Image
def take_screenshot(url, output_path='screenshot.png'):
chrome_options = Options()
chrome_options.add_argument('--headless')
service = ChromeService()
driver = webdriver.Chrome(service=service, options=chrome_options)
try:
driver.get(url)
abilities_block = driver.find_element(By.XPATH, '/html/body/div[1]/div[3]/div/div[4]/div[2]/div[1]/div/div[3]/div[1]/div/div[1]/div/div[2]')
location = abilities_block.location
size = abilities_block.size
screenshot_path = 'full_page_screenshot.png'
driver.save_screenshot(screenshot_path)
image = Image.open(screenshot_path)
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
block_image = image.crop((left, top, right, bottom))
block_image.save(output_path)
print(f"Скриншот сохранен в {output_path}")
finally:
driver.quit()
url = 'https://dota2protracker.com/hero/Invoker/new'
take_screenshot(url, output_path='block_screenshot.png')
from selenium import webdriver
def save_screenshot(driver: webdriver.Chrome, path: str = '/tmp/screenshot.png') -> None:
original_size = driver.get_window_size()
required_width = driver.execute_script('return document.body.parentNode.scrollWidth')
required_height = driver.execute_script('return document.body.parentNode.scrollHeight')
driver.set_window_size(required_width, required_height)
# driver.save_screenshot(path)
driver.find_element_by_tag_name('body').screenshot(path) # avoids scrollbar
driver.set_window_size(original_size['width'], original_size['height'])
from selenium import webdriver
url = 'https://stackoverflow.com/'
path = '/path/to/save/in/scrape.png'
driver = webdriver.Chrome()
driver.get(url)
el = driver.find_element_by_tag_name('body')
el.screenshot(path)
driver.quit()