簡體   English   中英

如何在Nightmare.js中處理JSON響應

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

有興趣知道是否有比使用.evaluate中的document.querySelector('*').textContent 使用Nightmare.js處理僅包含JSON數據的URL更好的方法或另一種方法?

這是一個例子。 此處的外部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或將其他帶有Nightmare.js的 node.js中的Nightmare.js一起使用來處理JSON響應,我完全了解並能夠自行使用其他庫(例如axios.js)來解決上述問題。

您不需要噩夢。 如果可以使用自動為您解析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...
});

這就是我的方法,實現起來更快,更容易記住。 我們可以像這樣使用它,直到有人創建了.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