+
63
-

selenium如何获取网页js加载渲染后的真实dom结构?

selenium如何获取网页js加载渲染后的真实dom结构?


网友回复

+
2
-

Selenium 默认获取的就是 JS 渲染后的真实 DOM,但关键在于 等待时机。如果在 JS 执行完成前调用获取方法,拿到的仍是初始 HTML。

下面提供一套生产环境常用的 Python 示例,包含显式等待、DOM 获取方式及注意事项:

完整示例代码(Python + Selenium 4)

from urllib.parse import urljoin, urlparse
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def get_rendered_dom_with_resolved_urls(target_url: str, wait_selector: tuple = (By.TAG_NAME, "body")):
    # Selenium 4.6+ 已内置驱动自动管理,直接调用即可
    chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_argument("--headless")
    chromeOptions.add_argument("--remote-debugging-port=9222")
    chromeOptions.add_a...

点击查看剩余70%

我知道答案,我要回答