2017-03-10 101 views
0

想知道是否有更好或其他方法來處理僅包含JSON數據的URL 使用Nightmare.js比在.evaluate中使用document.querySelector('*').textContent如何處理Nightmare.js中的JSON響應

這裏是一個例子;這裏的外部URL包含一個鏈接選擇字段的內容

{ 
    "baseDeliveryModelId":1, 
    "county": [ 
    {"id": "1000706000", "label": "Çukurova", "value": "Çukurova"}, 
    {"id": "1000707000", "label": "Sarıçam", "value": "Sarıçam" }, 
    {"id": "1000922000", "label": "Seyhan", "value": "Seyhan"}, 
    {"id": "1000921000", "label": "Yüreğir","value": "Yüreğir"} 
    ], 
    "listType":"DISTRICT_LIST" 
} 

一個sample.js代碼從URL (工作正常)

const Nightmare = require('nightmare'), 
    vo = require('vo'), 
    nightmare = Nightmare({show: true}); 


function counties(city) { 
    let countyUrl = `https://www.sanalmarket.com.tr/kweb/getCityDeliveryLocation.do?shopId=1&locationId=${city}&locationType=city&deliveryTypeId=0`; 
    return nightmare 
     .goto(countyUrl) 
     .evaluate(function() { 
      return (JSON.parse(document.querySelector('*').textContent)).county; 
     }) 
     .catch(function (err) { 
      console.log('Error: ', err); 
     }); 
} 


vo(function*() {  
    return yield counties('01');  
})((err, result) => {  
    if (err) return console.log(err); 
    console.log(result);  
}); 
只檢索該縣數據如下

注意:這個問題是關於使用Nightmare.js,或使用其他庫與Node.js中的Nightmare.js處理JSON響應,我完全知道並能夠使用其他庫,如他們的axios.js流ñ解決上述問題。

+0

@JonathanPortorreal:你知道nightmare.js是什麼嗎?如果沒有像nightmare.js這樣的東西,你不能做ajax調用。另一方面,如果您只需要JSON數據,則不需要執行ajax操作,只需執行http請求即可。 – slebetman

+0

@JonathanPortorreal:沒有像nightmare.js這樣的東西,你不能真正使用jquery,因爲jquery不能在node.js上工作。你可以在噩夢中使用jquery。 – slebetman

+0

@Zerka Mari是否有這個原因,你需要使用nightmarejs,你可以用http請求完成同樣的事情? –

回答

2

你不需要睡夢遊戲。 如果你可以使用自動分析你的JSON響應庫,例如請求承諾

const rp = require('request-promise'); 

rp({ 
url: 'https://www.sanalmarket.com.tr/kweb/getCityDeliveryLocation.do?shopId=1&locationId=${city}&locationType=city&deliveryTypeId=0', 
json: true 
}).then(function (data) { 
    console.log(data.country); 
}) 
.catch(function (err) { 
    // Crawling failed... 
}); 
+0

問題不是我是否需要或不需要nightmare.js,它是如果有更好的方法來處理使用nightmare.js的JSON。我完全知道其他圖書館,並在其他項目中使用它們,其中一個是你提到的另一個是axios。 –

2

這是我做的,它的速度更快實施,更容易記住。我們可以像這樣使用它,直到有人創建像.text().json()這樣的函數。

// Initiate nightmare instance 
var nightmare = Nightmare({ 
       show: true, 
       alwaysOnTop: false 
      }) 
      // go to a page with json response 
      .goto('https://api.ipify.org/?format=json') 
      .evaluate(() => { 
       // since all of the text is just json, get the text and parse as json, return it. 
       return JSON.parse(document.body.innerText) 
      }) 
      .then((data) => { 
      // then use it however we want 
       console.log(data) 
      });