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

รอให้หน้าเว็บโหลดเสร็จด้วย Selenium WebDriver Python (Explicit Wait)

ใช้ Explicit Wait** ร่วมกับ **Expected Conditions** เพื่อรอจนกว่าเงื่อนไขจะเป็นจริง (เช่น element ปรากฏ) แทนการรอเวลาคงที่

แนวคิด

  • WebDriverWait - คลาสสำหรับรอพร้อม timeout
  • ExpectedConditions - เงื่อนไขที่คาดหวัง (presence, visibility, clickable, etc.)
  • By - กลุ่ม locator strategies

ตัวอย่าง: รอจนกว่า <h1> จะปรากฏ

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")

try:
    wait = WebDriverWait(driver, 8)  # รอสูงสุด 8 วินาที
    wait.until(EC.presence_of_element_located((By.TAG_NAME, "h1")))
    print("Page load happened")
except TimeoutException:
    print("Timeout happened - no page load")
finally:
    driver.quit()

Expected Conditions ที่นิยมใช้

Conditionใช้เมื่อ
presence_of_element_locatedElement อยู่ใน DOM (ยังไม่ต้องมองเห็น)
visibility_of_element_locatedElement มองเห็นได้จริง (มีขนาด > 0)
element_to_be_clickableElement พร้อมคลิกได้ (visible + enabled)
title_contains / title_isตรวจสอบ title หน้าเว็บ
url_contains / url_matchesตรวจสอบ URL
alert_is_presentมี alert dialog แสดงอยู่

ข้อดีของ Explicit Wait

  • รอเพียงพอ (ไม่รอนานเกินไป)
  • จัดการ dynamic content / AJAX ได้ดี
  • ลด flaky tests
  • อ่านโค้ดง่าย เข้าใจง่าย
อย่าใช้ time.sleep() - เป็น anti-pattern ทำให้ test ช้าและไม่เสถียร