2017-05-17 31 views
0

我發佈我的問題希望有人可以幫助我, 我試圖抓住所有的具有屬性的機器人使用cheerio的一個屬性我向網址發出請求,它檢索我的HTML頁面中的字符串。cheerio - 選擇倍數類

<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <meta charset="utf-8"> 
 
    <title>test</title> 
 
    </head> 
 
    <body> 
 
    <a href="google.fr" class="test"></a> 
 
    <a href="yahoo.com" class="test"></a> 
 
    <a href="amazon.fr" class="test"></a> 
 
    <a href="linux.org" class="test"></a> 
 
    <a href="facebook.com" class="no_select"></a> 
 
    <a href="twitter.com" class="no_select"></a> 
 
    </body> 
 
</html>

我想這樣的事情

const cheerio = require('cheerio'); 
 
const page = `<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<meta charset="utf-8"> 
 
<title>test</title> 
 
</head> 
 
<body> 
 
<a href="google.fr" class="test"></a> 
 
<a href="yahoo.com" class="test"></a> 
 
<a href="amazon.fr" class="test"></a> 
 
<a href="linux.org" class="test"></a> 
 
<a href="facebook.com" class="no_select"></a> 
 
<a href="twitter.com" class="no_select"></a> 
 
</body> 
 
</html>` 
 
const $ = cheerio.load(page) 
 
const links = $('.test').each((index, elem) =>{ 
 
\t console.log(elem); 
 
}); 
 
console.log(links);

,但沒有一個巨大的成功。

我正在尋找一個解決方案來檢索一個數組,其中每個元素是href屬性好的鏈接有一個測試類使用cheerio。

感謝你的幫助=)

+0

我剛剛編輯的帖子=) –

回答

0

我終於找到解決辦法

const cheerio = require('cheerio'); 
 
const page = `<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<meta charset="utf-8"> 
 
<title>test</title> 
 
</head> 
 
<body> 
 
<a href="google.fr" class="test"></a> 
 
<a href="yahoo.com" class="test"></a> 
 
<a href="amazon.fr" class="test"></a> 
 
<a href="linux.org" class="test"></a> 
 
<a href="facebook.com" class="no_select"></a> 
 
<a href="twitter.com" class="no_select"></a> 
 
</body> 
 
</html>` 
 
const $ = cheerio.load(page) 
 
const links = $('.test').each((index, elem) =>{ 
 
\t console.log(elem.attribs.href); 
 
});

,它的工作,對不起disturbtion。