简体   繁体   English

如何在Nightmare.js中处理JSON响应

[英]How to handle JSON response in Nightmare.js

Interested to know if there is a better or another way to handle URLs that contain only JSON data using Nightmare.js than using document.querySelector('*').textContent within .evaluate? 有兴趣知道是否有比使用.evaluate中的document.querySelector('*').textContent 使用Nightmare.js处理仅包含JSON数据的URL更好的方法或另一种方法?

Here is an example; 这是一个例子。 the external URL here contains the following which is the contents of a linked select field 此处的外部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"
}

A sample.js code to retrieve just the county data from the URL (which works fine) 一个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);    
});

Note: The question is about using Nightmare.js , or using other libraries with Nightmare.js in node.js for handling JSON responses, I am fully aware and capable of using other libraries such as axios.js on their own to solve the above. 注意:问题是关于使用Nightmare.js或将其他带有Nightmare.js的 node.js中的Nightmare.js一起使用来处理JSON响应,我完全了解并能够自行使用其他库(例如axios.js)来解决上述问题。

You don't need nightmarejs. 您不需要噩梦。 if you can use a library that auto parse the json response for you, for example request-promise 如果可以使用自动为您解析json响应的库,例如request-promise

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...
});

This is how I did it, it's faster to implement, easier to remember. 这就是我的方法,实现起来更快,更容易记住。 We can use it like this until someone creates functions like .text() and .json() . 我们可以像这样使用它,直到有人创建了.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)
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM