gpt4 book ai didi

javascript - 在 Electron 中从网站上刮掉html标签

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:42 25 4
gpt4 key购买 nike

有没有办法在 Electron 中抓取网站。我的目标是能够访问网站并抓取 html 标签。我使用的是 Windows 机器,因此我启动了应用程序(npm start index.html)。我的想法是创建一个 .js 文件并使用 require (Url, function(err, resp,html){ }) 就像在 Node 中可以做的那样,但这在 Electron 中不起作用。此代码无法抓取页面并执行回调。我只想要 html。我怎样才能完成这件事?我进行回调的 app.js 文件中的代码是。

function scrape(callback){ 

var content = [];
var request = require('request');
var cheerio = require('cheerio');
var url = "http://www.amazon.com";



request(url, function(error, response, html){

if (error){

content.push('Error:', error);
}
if (response.statusCode !== 200) {

content.push('Invalid Status Code Returned:', response.statusCode);
}

content.push(html);
var $ = cheerio.load(html);


$('td').each(function (i, element) {


var a = $(this).prev();
var trimmed_a = a.text();

trimmed_a = trimmed_a.trim();
var str = trimmed_a.replace(/\s\s+/g,"");
var newStr = str.trim();

content.push(newStr);

});


})
callback(content);
}

module.exports = scrape;

回调工作正常,但代码未执行。有很多不明白的地方,请随意建设性地指导。我们的目标是能够用它抓取任何网站。

最佳答案

对于使用 Electron 抓取网站,我建议您使用 NightmareJs .

npm install nightmare

    var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });

nightmare
.goto('https://duckduckgo.com')
.type('#search_form_input_homepage', 'github nightmare')
.click('#search_button_homepage')
.wait('#zero_click_wrapper .c-info__title a')
.evaluate(function() {
return document.querySelector('#zero_click_wrapper .c-info__title a').href;
})
.end()
.then(function(result) {
console.log(result);
})
.catch(function(error) {
console.error('Search failed:', error);
});

关于javascript - 在 Electron 中从网站上刮掉html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40700735/

25 4 0