2015-07-06 40 views
5

從Casper.js遷移到Selenium以獲取更多工具。Selenium Webdriver迭代並瀏覽node.js中的多個鏈接

試圖遍歷多個鏈接並使用node.js和selenium-webdriver導航它們。

無法找到任何文檔或示例,無論我嘗試運行哪個循環,都會收到錯誤。

iLinkCount = oLinks.length; 
    console.log(oLinks); 
    console.log(iLinkCount); 

Code above outputs the link count to the console but I am unable to get their href tags to continue on with my testing.

driver.findElements(webdriver.By.css('snip')).then(function(oLinks) { 
// driver.findElements(webdriver.By.xpath("//snip")).then(function(oLinks) { 
    iLinkCount = oLinks.length; 
    console.log(oLinks); 
    console.log(iLinkCount); 

    // for(var oLink in oLinks){ 
    //  var sLink = oLink.getAttribute('href'); 
    //  console.log(sLink); 
    // } 


    for(var i = 0; i < iLinkCount; i++){ 
     var oLink = oLinks.get(i); 
     console.log(oLink); 
     // var sLink = oLinks[ i ].getAttribute('href'); 
     // console.log(sLink); 
    } 
}); 

每一個循環我嘗試使用遍歷的鏈接我得到一個錯誤:

TypeError: undefined is not a function

這有什麼錯我的循環?

關於驅動硒-webdriver與節點的示例/真正用法文檔的任何好的參考?

經過廣泛搜索後,所有似乎都是半記錄的都是java/python樣本。

回答

5

我會說this documentation是相當不錯的。

與您的代碼的問題是,當你在看文檔,findElements返回WebElement一個數組,有沒有get方法,有一點我的心得是,如果你打算在JavaScript與selenium玩,你需要正確理解Promise的概念(並且確保不要做任何反諾模式),簡單地說,大多數情況下,你與驅動程序交談(調用一些方法),你會得到一個承諾,作爲回報有你想要的價值,而不是實際價值本身。

基於CSS選擇retriving HREF功能:

function getAllHrefs(driver, cssValue){ 
    var selector; 
    if(!cssValue) selector = By.tagName('a'); 
    else   selector = By.css(cssValue); 
    return driver.findElements(selector).then(function(oLinks){ 
     var allPromises = oLinks.map(function(oLink){ 
      return oLink.getAttribute('href'); 
     }); 
     return Driver.promise.all(allPromises); 
    });  
} 

例如用於上述功能:

var dummyPage = 'http://google.com' 
, Driver = require('selenium-webdriver') 
, By = require('selenium-webdriver').By 
, chrome = require('selenium-webdriver/chrome') 
, driver 
; 


driver = getDriverInstance(); 
driver.get(dummyPage); 
getAllHrefs(driver).then(function(hrefs){ 
    console.log('got hrefs: ', hrefs.length, hrefs); 
}); 


function getAllHrefs(driver, cssValue){ 
    var selector; 
    if(!cssValue) selector = By.tagName('a'); 
    else   selector = By.css(cssValue); 
    return driver.findElements(selector).then(function(oLinks){ 
     var allPromises = oLinks.map(function(oLink){ 
      return oLink.getAttribute('href'); 
     }); 
     return Driver.promise.all(allPromises); 
    });  
} 

function getDriverInstance(){ 
    var driverInstance = new Driver.Builder() 
     .usingServer() 
     .withCapabilities({ 
      browserName: 'chrome' 
     }) 
     .setChromeOptions(
      new chrome.Options() 
       .addArguments('--privileged') 
       .addArguments('--no-sandbox') 
     ) 
     .build(); 
    return driverInstance; 
} 
相關問題