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

ตั้งค่า Default Timeout ใน Selenium Python WebDriver

Selenium มี 2 วิธีตั้งค่า timeout เริ่มต้น:

1. set_page_load_timeout() - Timeout การโหลดหน้าเว็บ

driver.set_page_load_timeout(5)  # วินาที

ถ้าโหลดเกิน 5 วินาที จะโยน TimeoutException

2. implicitly_wait() - Implicit Wait (Global Wait)

driver.implicitly_wait(5)  # วินาที

รอ element ทุกตัวสูงสุด 5 วินาที ก่อนโยน NoSuchElementException (ไม่ใช่ TimeoutException)

ความแตกต่าง

คุณสมบัติset_page_load_timeoutimplicitly_wait
ขอบเขตการโหลดหน้าเว็บทั้งหน้าการหา element ทุกตัว
ExceptionTimeoutExceptionNoSuchElementException
ใช้เมื่อหน้าเว็บโหลดช้าElement รีดิ้งช้า (AJAX, dynamic content)

ตัวอย่างโค้ด

Page Load Timeout

from selenium import webdriver

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

Implicit Wait

from selenium import webdriver

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

แนวทางปฏิบัติที่ดี (Best Practice)

  • ใช้ Explicit Wait (WebDriverWait) สำหรับเงื่อนไขเฉพาะ - แม่นยำกว่า
  • หลีกเลี่ยง implicit wait ยาวเกินไป ทำให้ test ช้า
  • ตั้ง page load timeout เหมาะสม (10-30 วินาที)