提问人:Prince 提问时间:9/26/2023 最后编辑:egleasePrince 更新时间:9/26/2023 访问量:61
如何使用 Selenium 检索 dataLayer 对象?
How to retrieve dataLayer Object using Selenium?
问:
我正在尝试找到一种方法,使用 selenium webdriver 通过 java 从网站中提取数据层对象。 我正在使用 jsExecutor.executeScript 将“windows.dataLayer”命令传递到 Chrome 控制台选项卡并将数据解析为 ArrayList。但是,每当我运行代码时,它总是失败并吐出以下内容:
WebDriverException:未知错误:节点中缺少 backendNodeId
我尝试过的事情:
JavaScript 命令的各种替代品:
“返回 dataLayer;”
“返回 JSON.stringify(window.dataLayer);”
“返回 console.log('dataLayer')”;
重新启动计算机
通过 Taskkill /F /IM chromedriver.exe /T 从 cmd 杀死所有 ChromeDriver 实例
硒 v4.8.3 Chrome驱动程序 v116
我的代码:
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.ArrayList;
import java.time.Duration;
public class Example {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
// Get the website.
driver.get("https://mvnrepository.com/");
// Create a WebDriverWait object.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for the page to finish loading.
wait.until(ExpectedConditions.jsReturnsValue("return document.readyState === 'complete';"));
// Wait for the dataLayer object to become present.
wait.until(ExpectedConditions.jsReturnsValue("return (typeof dataLayer !== 'undefined');"));
// Wait for the dataLayer object to be an object.
wait.until(ExpectedConditions.jsReturnsValue("return (typeof dataLayer === 'object');"));
// Get the JavascriptExecutor object.
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
// Try to retrieve the dataLayer object.
try {
ArrayList<String> dataLayer = (ArrayList<String>) jsExecutor.executeScript("return window.dataLayer;");
} catch (Exception e) {
// Handle the exception.
e.printStackTrace();
}
// Print the dataLayer object.
System.out.println(dataLayer);
// Quit the driver.
driver.quit();
}
}
错误:
org.openqa.selenium.WebDriverException: unkown error: backendNodeId is missing in a node
at Example.Main (Example.java: 19) --\> ArrayList\<String\> dataLayer = (ArrayList\<String\>) jsExecutor.executeScript("return dataLayer;");
答: 暂无答案
评论