[英]How to use selenium webdriver to click on links
How can I use selenium webdriver
to get all links from the page that have the property a[href*=/simulation/form/]
and then open and close each of them?如何使用selenium webdriver
从具有属性a[href*=/simulation/form/]
的页面中获取所有链接,然后打开和关闭每个链接?
I tried the following code but it returns TypeError: link.click is not a function
我尝试了以下代码,但它返回TypeError: link.click is not a function
var simLinks = driver.findElements(By.css('a[href*=/simulation/form/]'));
for(var link in simLinks){
link.click();
driver.wait(30000);
driver.back();
}
If I do console.log(simLinks.length)
it returns undefined
如果我做console.log(simLinks.length)
它返回undefined
Instead, it works perfect if I try to open a single link of that type:相反,如果我尝试打开该类型的单个链接,它会完美运行:
var simLinks = driver.findElement(By.css('a[href*=/simulation/form/]')).click();
Use the util.inspect()
function to inspect objects:使用util.inspect()
函数检查对象:
const util = require('util');
...
console.log(util.inspect(simLinks));
Once you do that, you will see that simLinks
is a ManagedPromise
, so you need to change your code as follows to make it work:完成后,您将看到simLinks
是ManagedPromise
,因此您需要按如下方式更改代码以使其工作:
driver.findElements(By.css('a[href*="/simulation/form/"]')).then(function (simLinks) {
for (let link of simLinks) {
link.click();
driver.wait(until.urlContains('/simulation/form/', 30000));
driver.navigate().back();
}
});
The problem with that, however, is that only the first click works, but once you navigate back there is a legitimate StaleElementReferenceError
- the page has indeed changed and the next element in the loop is no longer attached to the visible page.然而,问题在于只有第一次点击有效,但是一旦你导航回来,就会出现一个合法的StaleElementReferenceError
- 页面确实发生了变化,循环中的下一个元素不再附加到可见页面。 Therefore, a better strategy would be to collect the link addresses instead and use these with driver.navigate().to(link)
:因此,更好的策略是收集链接地址并将它们与driver.navigate().to(link)
:
driver.findElements(By.css('a[href*="/simulation/form/"]')).then(function (simLinks) {
var hrefs = simLinks.map(link => link.getAttribute('href'));
for (let link of hrefs) {
driver.navigate().to(link);
driver.wait(until.urlContains('/simulation/form/', 30000));
driver.navigate().back();
}
});
I believe you should be using:我相信你应该使用:
console.log(simLinks.size()) console.log(simLinks.size())
I don't know if the () is required in javascript - it is in java.我不知道 javascript 中是否需要 () - 它在 java 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.