ใน Python Selenium สามารถดึง HTML ภายใน (innerHTML) ของ WebElement ได้ 2 วิธี
วิธีที่ 1: ใช้ get_attribute('innerHTML')
html = element.get_attribute('innerHTML')
วิธีที่ 2: ใช้ JavaScript Executor
html = driver.execute_script("return arguments[0].innerHTML;", element)
ตัวอย่างโค้ดสมบูรณ์ (วิธีที่ 1)
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
driver.get("https://www.example.com")
# หาองค์ประกอบ (ตัวอย่าง: h4)
element = driver.find_element(By.CSS_SELECTOR, "h4")
# ดึง innerHTML
html = element.get_attribute('innerHTML')
print("HTML code of element:", html)
driver.quit()
ตัวอย่างโค้ดสมบูรณ์ (วิธีที่ 2)
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
driver.get("https://www.example.com")
element = driver.find_element(By.CSS_SELECTOR, "h4")
# ใช้ JavaScript Executor
html = driver.execute_script("return arguments[0].innerHTML;", element)
print("HTML code of element:", html)
driver.quit()
ผลลัพธ์ตัวอย่าง
หาก HTML ต้นฉบับเป็น:
<h4>You are browsing the best resource for <b>Online Education</b></h4>
ผลลัพธ์ innerHTML จะเป็น:
You are browsing the best resource for <b>Online Education</b>
ความแตกต่างระหว่าง innerHTML และ outerHTML
| เมธอด/Property | คำอธิบาย | ตัวอย่างผลลัพธ์ |
|---|---|---|
get_attribute('innerHTML') |
เนื้อหาภายในแท็ก (ไม่รวมแท็กตัวเอง) | Hello <b>World</b> |
get_attribute('outerHTML') |
โค้ด HTML ทั้งหมดรวมแท็กตัวเอง | <h4>Hello <b>World</b></h4> |
JS: arguments[0].innerHTML |
เหมือน innerHTML | เหมือนข้างต้น |
JS: arguments[0].outerHTML |
เหมือน outerHTML | เหมือนข้างต้น |
เมื่อไหร่ควรใช้วิธีไหน?
- get_attribute: ใช้งานง่าย เร็ว พอสำหรับส่วนใหญ่
- execute_script: เมื่อ get_attribute ไม่ทำงาน (เช่น Shadow DOM, หรือองค์ประกอบที่ซ่อนอยู่)