node使用http爬取 cnode api数据时,json.parse报错
发布于 5 年前 作者 AlvinLicuntao 3358 次浏览 来自 问答

报错信息如下 image.png

用浏览器访问接口,得到的数据如下:image.png

贴上代码:

var https = require('https') // Node.js提供了http模块,用于搭建HTTP服务端和客户端

function sendRequest(path) {
  return new Promise(function (resolve, reject) {
    https.get({
      path: path,
      hostname: 'cnodejs.org',
      headers: {
        Accept: 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
      }
    }, function (res) {  //发送get请求
      var result = null
      res.on('data', function (data) {
        result = '' + data
      })
      res.on('end', function () {
        resolve(JSON.parse(result, (key, value) => {
          if (['content', 'title'].indexOf(key) > -1) {
            return ''
          } else {
            return value
          }
        }))
      })
    }).on('error', function (e) {
      reject(e)
    })
  })
}

sendRequest('/api/v1/topics').then(res => {
  console.log(res.data.length)
}).catch(e => {
  console.log(e)
})

请问有没有什么办法可以解决这个问题?

4 回复

没弄明白是啥问题,换成 request模块请求就可以

 var result = ''
 res.on('data', function (data) {
   result += data
 })

不一定是换行符,有时候输出爬取的内容,部分中文字符会变成问号字符,不可识别。换了request后也还是会出现一些转换问题。最终我采用爬取对应的html然后cheerio解析的方式不过,有些字段在页面找不到

@AlvinLicuntao 你有试过我给你的东西吗?这样写不会有什么问号字符,和网页打开https://cnodejs.org/api/v1/topics一样的 你写的对应部分有问题,而不是JSON.parse的问题。实际上是JSON解析的时候,result都没有获取完整,直接有一个/r分隔了

// 另外request也没发现什么问号字符
require('request')('https://cnodejs.org/api/v1/topics', (err, res, body) => console.log(JSON.parse(body)))
回到顶部