2017-05-25 34 views
0

我最近開始開發一個Node js應用程序,它使用控制器中的Selenium從網頁中獲取項目列表,並且想要將獲取的項目列表作爲JSON響應返回。返回帶有節點js的對象的列表

exports.read_all_products = function (req, res) { 
    var driver = new webdriver.Builder().forBrowser('phantomjs').build(); 
    driver.get('https://www.test.com/products?PC=' +req.params.category);  
    driver.wait(until.elementLocated(By.className('product-slide-all')), 20000, 'Could not locate the element within the time specified'); 

    driver.findElements(By.className("product-slide-all")).then(function (elements) { 
     var arr = []; 
     elements.forEach(function (element) { 
     element.getAttribute("innerHTML").then(function (html) { 
      const dom = new JSDOM(html); 
      var obj = new Object(); 
      obj.product_name = dom.window.document.querySelector(".product-name").textContent; 
      obj.product_code = dom.window.document.querySelector(".product-code").textContent; 
      obj.price = dom.window.document.querySelector(".product-price").textContent; 
      arr.push(obj); 
     }); 
    }); 
    res.json(arr); 
    }); 
} 

問題是我總是得到一個空的JSON響應,即使項目被添加到數組中。我想知道處理這種情況的正確方法。

謝謝。

+0

你可以嘗試移動你的'res.json(arr);'一個級別? ('});')之前? –

+0

不,然後我得到一個錯誤,說'發送後無法設置標題'。 – Lakmal

+0

哦。在這種情況下,你可以嘗試將你的'res.json(arr);'改寫爲'JSON.parse(JSON.stringify(arr))'? –

回答

0

最後我能得到它webdriver.promise.map的工作有所幫助。

將網頁驅動程序的HTML提取移至獨立函數。

var findItems = function (category) { 
var driver = new webdriver.Builder().forBrowser('phantomjs').build(); 
var map = webdriver.promise.map; 
driver.get('https://www.test.com?PC=' + category); 
driver.wait(until.elementLocated(By.className('product-slide-all')), 30000, 'Could not locate the element within the time specified'); 
    var elems = driver.findElements(By.className("product-slide-all")); 
     return map(elems, elem => elem.getAttribute("innerHTML")).then(titles => { 
     return titles; 
    }); 
} 

然後像波紋管響應處理函數中調用它,

exports.read_all_products = function (req, res) { 
findItems(req.params.category).then(function (html) { 
    var value; 
    var arr = []; 
    Object.keys(html).forEach(function (key) { 
     value = html[key]; 
     const dom = new JSDOM(value); 
     var obj = new Object(); 
     obj.product_name = dom.window.document.querySelector(".product-name").textContent; 
     obj.product_code = dom.window.document.querySelector(".product-code").textContent; 
     obj.price = dom.window.document.querySelector(".product-price").textContent; 
     arr.push(obj); 
    }); 
    res.json(arr); 
}) 
}; 

它在this stack overflow answers描述。