英文:
Selenium JavascriptExecutor doesnt return anything
问题
我初始化了一个JavascriptExecutor,但它没有返回我想要的内容。对象始终为空。
SeleniumDriver driver = new SeleniumDriver(DriverType.ChromeDriver);
driver.get("https://www.xxxxxx.info/");
driver.waitForPageToBeLoaded();
JavascriptExecutor js = (JavascriptExecutor) driver.getWebDriver();
Object ob = js.executeScript("___grecaptcha_cfg.clients[0]");
这是控制台中显示的内容:
为什么我无法通过JavascriptExecutor获取它?
英文:
I initialized a JavascriptExecutor but it doesn't return me what I want. Object is always null.
SeleniumDriver driver = new SeleniumDriver(DriverType.ChromeDriver);
driver.get("https://www.xxxxxx.info/");
driver.waitForPageToBeLoaded();
JavascriptExecutor js = (JavascriptExecutor) driver.getWebDriver();
Object ob = js.executeScript("___grecaptcha_cfg.clients[0]");
Here what it gives me in console:
Why am I not able to get it via JavascriptExecutor?
答案1
得分: 2
// 你的 JS 脚本应该返回它。尝试以下更改
Object ob = js.executeScript("return ___grecaptcha_cfg.clients[0];");
所以你的代码将会是这样的
SeleniumDriver driver = new SeleniumDriver(DriverType.ChromeDriver);
driver.get("https://www.xxxxxx.info/");
driver.waitForPageToBeLoaded();
JavascriptExecutor js = (JavascriptExecutor) driver.getWebDriver();
Object ob = js.executeScript("return ___grecaptcha_cfg.clients[0];");
因为它是一个 JS 对象 JSON,所以它会抛出循环引用异常
你可以使用以下 JS 代码将其转换为 JSON
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(___grecaptcha_cfg.clients[0], getCircularReplacer());
由于它是跨域 iframe,你可以像下面的代码一样使用它,因为 Chrome 会阻止它,如下面的图片所示
[![enter image description here][1]][1]
英文:
Your js script should return it.try the below changes
Object ob = js.executeScript("return ___grecaptcha_cfg.clients[0]");
so that your code will be like
SeleniumDriver driver = new SeleniumDriver(DriverType.ChromeDriver);
driver.get("https://www.xxxxxx.info/");
driver.waitForPageToBeLoaded();
JavascriptExecutor js = (JavascriptExecutor) driver.getWebDriver();
Object ob = js.executeScript("return ___grecaptcha_cfg.clients[0]");
Since it is the JS object json it throws circular reference exception
You can convert to json using below js code
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(___grecaptcha_cfg.clients[0], getCircularReplacer());
Since it is cross origin iframe you can use it as chrome blocks it as shown in image below
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论