动态页面的等待策略
掌握 Selenium 中的显式等待、隐式等待和流畅等待,让您的爬虫可靠地处理异步加载的内容。
动态页面的等待策略 是 CoddyKit 上的免费 Web Scraping & Bots 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web Scraping & Bots 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web Scraping & Bots 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Timing Problem
Dynamic pages render content after the initial HTML loads. If your scraper grabs an element before JavaScript injects it, you get a NoSuchElementException or empty data.
Waiting strategies tell Selenium to pause until the page is ready, making automation reliable instead of flaky.
Why Not Just sleep()
A fixed time.sleep(5) is tempting but bad: it wastes time when the page is fast and still fails when the page is slow. Smart waits poll until a condition is true, then continue immediately.
import time
time.sleep(5) # fragile: arbitrary, blocking, often wrongImplicit Waits
An implicit wait sets a global timeout. Selenium retries finding any element for up to that many seconds before failing.
Simple, but it applies to all lookups and cannot wait for arbitrary conditions like visibility or text.
driver.implicitly_wait(10) # seconds, applies globallyExplicit Waits
An explicit wait targets one specific condition. Use WebDriverWait with an expected_conditions check. This is the recommended approach for scraping.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, 'results'))
)Common Expected Conditions
The expected_conditions module covers most needs:
presence_of_element_locatedin the DOM.visibility_of_element_locatedis rendered and visible.element_to_be_clickableready for interaction.text_to_be_present_in_elementwaits for content.
EC.visibility_of_element_located((By.CLASS_NAME, 'price'))
EC.element_to_be_clickable((By.ID, 'load-more'))Waiting for Text
When you need a specific value to appear (for example a price loaded by an API call), wait on the text rather than mere presence.
WebDriverWait(driver, 15).until(
EC.text_to_be_present_in_element((By.ID, 'status'), 'Loaded')
)Fluent Waits
A fluent wait lets you tune the polling interval and ignore specific exceptions while waiting. Useful for slow APIs that throw transient errors.
wait = WebDriverWait(driver, timeout=20, poll_frequency=1,
ignored_exceptions=[StaleElementReferenceException])
wait.until(EC.presence_of_element_located((By.ID, 'data')))Handling Stale Elements
If the DOM re-renders, a stored element reference becomes stale. Re-fetch the element inside the wait or after the page settles instead of reusing the old handle.
from selenium.common.exceptions import StaleElementReferenceException
try:
el.click()
except StaleElementReferenceException:
el = driver.find_element(By.ID, 'btn')
el.click()Waiting for Page Load State
You can poll the document's readyState via JavaScript to confirm the whole page finished loading before scraping.
WebDriverWait(driver, 10).until(
lambda d: d.execute_script('return document.readyState') == 'complete'
)Combining Strategies Wisely
Best practice: avoid mixing implicit and explicit waits (they compound unpredictably). Pick explicit waits for scraping, keep timeouts realistic, and wait for the precise condition your data depends on.
A Reliable Pattern
Wrap waits in a helper so every lookup is robust. This keeps your scraping code clean and consistent.
def wait_for(driver, locator, timeout=10):
return WebDriverWait(driver, timeout).until(
EC.visibility_of_element_located(locator)
)
price = wait_for(driver, (By.CLASS_NAME, 'price')).textQuick Check
Test your understanding of waiting strategies.
Recap
You learned to handle asynchronous content with implicit, explicit, and fluent waits, target conditions like visibility and clickability, recover from stale elements, and avoid fragile fixed sleeps.
Reliable waiting is the foundation of stable dynamic-page scraping.
常见问题解答
「动态页面的等待策略」课时是免费的吗?
是的 — 「动态页面的等待策略」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Scraping & Bots 课程的其余内容,请升级到 CoddyKit PRO。 Web Scraping & Bots 课程共包含 4 节课。
「动态页面的等待策略」这节课中我会学到什么?
掌握 Selenium 中的显式等待、隐式等待和流畅等待,让您的爬虫可靠地处理异步加载的内容。 你通过在浏览器中直接运行的动手代码来练习 Web Scraping & Bots,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Web Scraping & Bots 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Web Scraping & Bots 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「动态页面的等待策略」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Web Scraping & Bots 课中编写并运行代码吗?
能。每节 Web Scraping & Bots 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。