Capture screenshot of an Element using Python Selenium WebDriver

服用這個範例,即可取得完整畫面的screen shot.

from selenium import webdriver
from PIL import Image

url = "http://your-url-here"
save_filename = "your-filename.png"

option = webdriver.ChromeOptions()
option.add_argument('--headless')
option.add_argument('--disable-gpu')
option.add_argument("--window-size=1280,1024")
option.add_argument("--hide-scrollbars")
driver = webdriver.Chrome(chrome_options=option)
driver.get(url)

scroll_width = driver.execute_script('return document.body.parentNode.scrollWidth')
scroll_height = driver.execute_script('return document.body.parentNode.scrollHeight')
driver.set_window_size(scroll_width, scroll_height)
driver.save_screenshot(save_filename)

element = driver.find_element_by_xpath("//div[@id='your_id_here']");
location = element.location;
size = element.size;
x = location['x'];
y = location['y'];
width = location['x']+size['width'];
height = location['y']+size['height'];
im = Image.open(save_filename)
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('your_corped_image.png')

除了完整畫面scrren shot,也可以單獨對element 做 save screen shot,範例:

img_captcha.screenshot('captcha.png')

相關文章:

[Python] 圖片降噪
https://stackoverflow.max-everyday.com/2019/06/python-opencv-denoising/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *