2016-11-16 63 views
0

我想從html元標籤中提取一些元數據。抓取的html中存在以下元標記。cheerio:麻煩選擇元屬性

<meta property="og:type" content="offer"/> 
<meta property="og:title" content='خانه ذرت با کورن داگ لذیذ و خوشمزه در تهران' /> 

我已經寫了下面的示例代碼,同時獲得OG的內容:從meta標籤標題特性:類型和OG

var request = require('request'); 
var cheerio = require('cheerio'); 

var a='http://someurl/'; 
getDealInfo(a); 


function getDealInfo(url){ 
    var options = { 
     url: encodeURI(url), 
     headers: { 
      'Accept' : '*/*', 
      'Cache-Control':'no-cache', 
     } 
    }; 
    request(options, function(error, response, html){ 
     if (!error && response.statusCode == 200) { 
      var $ = cheerio.load(html); 
      var title = $('meta[property="og:title"]').attr('content'); 
      console.log('title: ' + title); 
      var type = $('meta[property="og:type"]').attr('content'); 
      console.log('type: ' + type); 
     }else console.log('Error accessing Deal:' + response.statusCode + '\n'+error); 
    }); 
} 

我得到正確的內容 og:type and undefined for og:title,雖然這兩個屬性都是presen t在提取的html中。

有人可以幫我弄清楚爲什麼我不能得到屬性內容的og:標題

+0

Hi Amir,welcome to Stack Overflow!你能否更多地編輯你的問題以包含更多關於問題到底是什麼的細節? – Kezz101

+0

我根據網站所有者的要求更改了主要網址。 – Amir

回答

0

我注意到,html響應沒有元og:title

您可以通過看到:

request(options, function(error, response, html){ 
    fs.writeFile('./index.html', html) 
}) 

但是你可以使用needlehttps://www.npmjs.com/package/needle包代替request

var needle = require('needle') 
var results = [] 
needle.get(encodeURI(url), function(err, res) { 
    if (err) throw err 
    var $ = cheerio.load(res.body) 
    var title = $('meta[property="og:title"]').attr('content') 
    results.push({ 
     title: title 
    }) 
    fs.writeFile('./data.json', JSON.stringify(results)) 
}) 

輸出data.json文件與og:title續ent:

[ 
    { 
     "title": "خانه ذرت با کورن داگ لذیذ و خوشمزه در تهران" 
    } 
] 
+0

謝謝。這是工作。 – Amir