我现在越来越沮丧,我希望能在 stackexchange 上找到一些帮助。
首先要做的事情:我不是一个经验丰富的 Javascript 开发人员,可能根本不是一个经验丰富的开发人员,但我想我知道如何使用基本脚本 - 我知道一点 C#、Java 和 co.. 对于我目前的网络自动化脚本 我认为 catch 并尝试用 Javascript 编写是一个好主意,但现在我正处于一个阶段,我考虑从头开始使用另一种不那么令人困惑的语言。
拜托,谁能告诉我,我怎么能让我的代码从上到下以同步方式执行?
经过大量的谷歌搜索,到目前为止,我已经尝试了以下方法:
#! /usr/bin/env node
开始并使用 ./app.js
在终端中启动async
函数() await
在所有方法上()但即使是现在,当我运行脚本时,它还是会抛出很多
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'isDisplayed' of undefined
和类似的事情,让我猜想,那个节点正在异步运行我的一些方法/函数。在浏览器窗口启动和加载之前,这些异常就会在控制台中弹出。我在用:
* Selenium 网络驱动程序 3.6.0
* 火狐 60.0.2
* 节点 8.10.0
我的代码基本上是这样的:
const {Builder, By, Key, until, manage} = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');
const webdriver = require('selenium-webdriver');
const fs = require('fs');
//
// declaring lots of global variables, I need in my functions
//
async function init(){
let options = await new firefox.Options()
.setProfile('/home/ruphus/.mozilla/firefox/selenium_profile.backtesting');
let driver = await new webdriver.Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
await driver.get('https://www.someurl.com/')
.then(openStrategySettings())
.then(btnStrategySettings.click());
// ... defining webelements/locations to the previously created objects - using xpath
inputPeriod = await driver.findElement(By.xpath("//div[@id='header-toolbar-intervals']/div/div/div"));
}
async function openStrategySettings() {
if (!someWebelement.isDisplayed()){
await tabStrategyTester.click();
}
}
async function inputValue(element, value) {
await element.sendKeys(Key.BACK_SPACE + Key.BACK_SPACE + value.toString());
}
async function run(){
// this is the main function with a couple of for loops and array.forEach(function()... things
}
init();
run();
据我了解,我正在使用我的
async init()
启动 webdriver 和 firefox功能。在这里,我对所有这些方法都使用了 await。启动 webdriver/firefox 后,我将 Object 变量定义到位置(我希望在浏览器启动并加载时发生这种情况)。但不知何故,我不明白为什么,该脚本似乎运行了我的所有功能以及在启动脚本后可以直接找到的所有代码。实际上,它似乎等待最后加载浏览器。在它最终加载之前,我得到了几个(8)
UnhandledPromiseRejectionWarning
..UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'sendKeys' of undefined
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'click' of undefined
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'isDisplayed' of undefined
我真的很感激这里的一些帮助。
最佳答案
答案让async
/await
纯粹同步运行的功能似乎是让它只运行一个功能。
我的意思是不能先init();
用于初始化浏览器和变量和东西和之后 那个电话run();
对于自动化本身。
而是应该构建一个小函数 main(),它调用这两个函数:
async main(){
await init;
await run();
}
main();
这似乎与异步运行有关。尽管如此,我仍然在为
await driver.sleep(1000);
烦恼,这似乎没有按预期工作。通过进一步的谷歌搜索,我还阅读了 here关于 webdriver-sync .但这是关于该主题的相当古老的评论。我不太确定 的最新情况如何网络驱动程序同步 是。我可能会尝试一段时间。
如果有人有关于如何解决的更多信息,例如不工作
await driver.sleep(1000);
方法,内使用array.forEach(async function(entry){
for(){
for(){
await driver.sleep(1000);
}
}
}
我会很高兴阅读。
关于javascript - Selenium:如何编写同步 Selenium 自动化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51032222/