Selenium 4+ รองรับการถ่ายรูปเฉพาะ WebElement โดยตรง ด้วยเมธอด .screenshot()
Syntax
element = driver.find_element_by_xpath("//img[@title='Tutorialspoint']")
element.screenshot("logo.png")
ตัวอย่างเต็ม
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/index.htm")
# หา element logo
logo = driver.find_element_by_xpath("//img[@title='Tutorialspoint']")
# ถ่ายรูปเฉพาะ logo
logo.screenshot("logo.png")
print("Screenshot saved as logo.png")
driver.quit()
ผลลัพธ์
สร้างไฟล์ logo.png ในโฟลเดอร์โปรเจกต์ - เป็นรูปเฉพาะ logo ไม่ใช่หน้าจอทั้งหมด
วิธีอื่น: ถ่ายหน้าจอเต็มแล้ว Crop (Selenium 3 หรือ fallback)
from PIL import Image
# ถ่ายหน้าจอเต็ม
driver.save_screenshot("full.png")
# หาตำแหน่งและขนาด element
element = driver.find_element_by_xpath("//img[@title='Tutorialspoint']")
location = element.location
size = element.size
# Crop ด้วย Pillow
img = Image.open("full.png")
left = location['x']
top = location['y']
right = left + size['width']
bottom = top + size['height']
img.crop((left, top, right, bottom)).save("logo_cropped.png")
เปรียบเทียบ
| วิธี | ข้อดี | ข้อเสีย |
|---|---|---|
| element.screenshot() | ง่าย เร็ว ไม่ต้อง library เพิ่ม | ต้อง Selenium 4+ |
| Full screenshot + crop | ทำงานได้ทุกเวอร์ชัน | ซับซ้อน ต้อง Pillow ช้ากว่า |