2017-03-10 60 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) 
      });