[英]Selenium: How to Inject/execute a Javascript in to a Page before loading/executing any other scripts of the page?
[英]Executing page scripts before retrieving it's contents
我有一個頁面,我需要在其中自動執行一些任務並抓取一些數據,但該頁面在加載后運行一些 JS 以將一些數據注入 DOM; 我無法攔截(無論如何都不是一個好的格式),我希望找到一個快速且不消耗內存的解決方案。
我試圖自己獲取腳本並使用一些無頭驅動程序(即 phantomJs)執行它們,但它沒有更新頁面源,我不知道如何從中檢索更新的 DOM
var page = GetWebPage(url);
var scripts = page.Html.QuerySelectorAll("script");
var phantomDriver = new PhantomJSDriver(PhantomJSDriverService.CreateDefaultService(Directory.GetCurrentDirectory()));
phantomDriver.Navigate().GoToUrl(url);
foreach (var script in scripts)
phantomDriver.ExecuteScript(script.InnerText);
var at = phantomDriver.PageSource;
您可以使用“等待”。 根據此鏈接,Selenium 具有隱式和顯式等待。 下面的示例使用顯式等待。
要使用顯式等待,請使用WebDriverWait
和ExpectedConditions
。 我不確定您使用的是什么語言,但這里有一個 Python 示例。 這在 try-catch 塊中使用WebDriverWait
,允許timeout
秒數滿足指定的ExpectedConditions
。 截至 2019 年 6 月,條件適用於:
python中的示例代碼:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
url = 'https://stackoverflow.com/questions/56724178/executing-page-scripts-before-retrieving-its-contents'
target = (By.XPATH, "//div[@class='gravatar-wrapper-32']")
timeout = 20 # Allow max 20 seconds to find the target
browser = webdriver.Chrome()
browser.get(url)
try:
WebDriverWait(browser, timeout).until(EC.visibility_of_element_located(target))
except TimeoutException:
print("Timed out waiting for page to load")
browser.quit()
重要的一點是在try
和except
之間,您可以修改它以使用您感興趣的特定“預期條件”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.