javascript 如何使用 WebDriverJS 捕获 Selenium 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28636402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I catch Selenium Errors using WebDriverJS
提问by Arcv2
So I am using the JavaScript implementation of Selenium, WebDriverJS. As with any web browser automation the biggest hurdle is getting the code slow down long enough for page elements to load. My solution is this:
所以我使用了 Selenium 的 JavaScript 实现,WebDriverJS。与任何 Web 浏览器自动化一样,最大的障碍是让代码放慢足够长的时间以加载页面元素。我的解决方案是这样的:
for each element I want to interact with I have a code block like this
对于我想与之交互的每个元素,我都有一个这样的代码块
xpath = "//div[@id='gs_lc0']/input[@id='gbqfq']"
driver.wait(function(){
return waitForElement(xPath,driver);
});
try{
element = driver.findElement(webdriver.By.xpath(xPath));
}catch(e){
console.log("Wait Function False Positive")
}
element.sendKeys("Let Me Google That For You\n";
with this as the function repeated in the wait function
以此作为在等待函数中重复的函数
var waitForElement = function(path, driver){
console.log("try: " + path)
try{
driver.findElement(webdriver.By.xpath(path));
}catch (e){
console.log("FAILURE")
return false;
}
console.log("SUCCESS")
return true;
}
now this code will work sometimes but othertimes it won't. I suppect the wait function isn't working at all and I'm just getting lucky webpage load times. So to test this theory I added the try function to the code block I cant even get the "NoSuchElementError" to be caught. So the brunt of my question is if there is some other way to form the tryCatch function so these errors will be caught.
现在这段代码有时会起作用,但有时不会。我认为等待功能根本不起作用,而且我只是幸运地获得了网页加载时间。所以为了测试这个理论,我在代码块中添加了 try 函数,我什至无法捕捉到“NoSuchElementError”。所以我的问题首当其冲是是否有其他方法可以形成 tryCatch 函数,以便捕获这些错误。
Also here is what the head of my code looks like if want a full reproduction
如果想要完整复制,这也是我的代码头部的样子
var webdriver = require('selenium-webdriver'), element
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
driver.get('google.com');
回答by Louis
bagelmaker's suggestion of using findElements
is not a bad one. That's usually what I do when I want to check whether an element exists rather than fiddle with exceptions.
bagelmaker 的使用建议findElements
还不错。当我想检查元素是否存在而不是摆弄异常时,这通常是我所做的。
However, for the sake of completeness, here is how you'd deal with the error generated when an element does not exist:
但是,为了完整起见,以下是处理元素不存在时生成的错误的方法:
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
driver.get('http://www.google.com');
driver.findElement(webdriver.By.id("fofofo")).then(null, function (err) {
if (err.name === "NoSuchElementError")
console.log("Element was missing!");
});
driver.quit();
The second argument to then
is an errback which is called if findElement
fails. Because selenium-webdriver
operates with promises, this is how you have to catch the error. Using try...catch
cannot work because Selenium does not start working right away; the work that you ask Selenium to do with findElement
is performed at an undetermined time in the future. By that time the JavaScript execution would have moved out of your try...catch
.
的第二个参数then
是一个 errback,如果findElement
失败则调用它。因为selenium-webdriver
使用 promise 操作,这就是您必须捕获错误的方式。使用try...catch
无法工作,因为 Selenium 不会立即开始工作;你要求 Selenium 做的工作findElement
是在未来的不确定时间执行的。到那时,JavaScript 执行将移出您的try...catch
.
The code above searches for an element with an id
value of fofofo
, which does not exist and fails.
上面的代码搜索id
值为的元素,该元素fofofo
不存在并失败。
回答by vivanov
You can also catch that error in a chained "catch" method:
您还可以在链接的“catch”方法中捕获该错误:
driver.findElement(webdriver.By.id("fofofo")).then(() => {
// do some task
}).catch((e) => {
if(e.name === 'NoSuchElementError') {
console.log('Element not found');
}
})
And if you're using async/await, you can do something like:
如果您使用 async/await,您可以执行以下操作:
try {
await driver.findElement(webdriver.By.id("fofofo"));
// do some task
}
catch (e) {
if (e.name === 'NoSuchElementError')
console.log('Element not found');
}
回答by bagelmakers
I would recommend reading up on explicit and implicit waits. A summary, explicit waits will poll the website until a specific condition is filled, while an implicit wait is more general and will wait a specified amount of time for a command to execute. In your case, I would refer to this previous question, which was resolved by using:
我建议阅读显式和隐式等待。总而言之,显式等待将轮询网站,直到满足特定条件,而隐式等待更为普遍,将等待指定的时间来执行命令。在你的情况下,我会参考这个以前的问题,这是通过使用解决的:
driver.wait(function() {
return driver.findElement(webdriver.By.xpath(xPath)).isDisplayed();
}, timeout);
OR
或者
driver.wait(function() {
return driver.isElementPresent(locator);
}, timeout);
Please comment if there is any clarification you need.
如果您需要任何说明,请发表评论。
EDIT:
编辑:
I mistook the question. An alternate method to catch a NoSuchElementError is to use the method findElements
which is documented here, and has an example implementation here. If no element exists, it will return a list of size 0. This way, an exception isn't thrown, and you can determine if it exists by the size of the list.
我误会了问题。捉NoSuchElementError的另一种方法是使用方法findElements
,其是记录在这里,并具有一示例实现这里。如果不存在元素,则返回一个大小为0的列表,这样就不会抛出异常,可以通过列表的大小判断是否存在。
I hope this is a better answer for your question.
我希望这是您问题的更好答案。