我有一个用例,其中我需要调用外部API,解析返回的JSON,并在使用Node JS编写的Selenium脚本中填充网页中的表单字段。
如下所示:
// in Selenium script get the form field
let inputElement = await getElementById(driver, "my-id");
// then call an API including callback function
// in the callback function with the JSON response from the API
const myText = response.data.text;
await inputElement.sendKeys(myText,Key.ENTER);
实际上,我甚至不确定从哪里开始-因为我将向作为Selenium脚本一部分运行的现有异步代码添加异步代码( API调用并等待回调中的响应)。并且我不需要丢失对web驱动程序和input元素的引用。
一些建议和建议会对我有很大的帮助。
发布于 2021-05-14 18:40:22
如果你正在使用node的内置https模块,你可以这样做。
const { Builder, By, Key, until } = require("selenium-webdriver");
const https = require("https");
(async function example() {
let driver = await new Builder().forBrowser("chrome").build();
try {
await driver.get("http://www.google.com/ncr");
await https.get("https://jsonplaceholder.typicode.com/users/1", (resp) => {
let data = "";
resp.on("data", (chunk) => {
data += chunk;
});
resp.on("end", async () => {
// console.log(JSON.parse(data)["name"]);
await driver
.findElement(By.name("q"))
.sendKeys(JSON.parse(data)["name"], Key.RETURN);
});
});
await driver.wait(until.titleContains("- Google Search"), 1000);
} finally {
await driver.quit();
}
})();
或者,如果您已经在使用axios之类的库,那么可以这样做。
const { Builder, By, Key, until } = require("selenium-webdriver");
const axios = require("axios");
(async function example() {
let driver = await new Builder().forBrowser("chrome").build();
try {
await driver.get("http://www.google.com/ncr");
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/users/1"
);
await driver.findElement(By.name("q")).sendKeys(data["name"], Key.RETURN);
await driver.wait(until.titleContains("- Google Search"), 1000);
} finally {
await driver.quit();
}
})();
希望这就是你要找的..
https://stackoverflow.com/questions/67532524
复制相似问题