Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ถ่ายรูปหน้าจอส่วนหนึ่ง (Partial Screenshot) ด้วย Selenium Python

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 ช้ากว่า