我正在尝试从服务器端进行点击。
我正在使用nodeJS,但无法使用JQuery功能。
我将点击 .next
类。
这就是我要做的:
while (nbrPage > 0)
{
//my scraping code
nbrPage--;
$('.next').click();
}
请注意,要抓取的 html 代码如下所示:
<span class="next">
<a id="nextPage-159c6fa8635" class="page" href="/blablabla"></a>
</span>
有谁知道如何在NodeJS代码中使用JQuery方法或者如何在NodeJS中制作点击功能?
编辑:我正在抓取一个网站,我想在每个分页上循环并从每个页面中抓取我的数据。为此,我需要进入下一页并单击下面的 html 代码。换句话说,我将在我的 Node js 代码中使用诸如 $('.next').click()
之类的 JQuery 函数(使用 request
和 cheerio
)。
请注意,我不想处理点击事件,我希望进行点击。
感谢您的帮助
最佳答案
Cheerio 是一个非常有用的工具,它允许您在 Node.JS 中使用 jQuery。您可以在 - https://github.com/cheeriojs/cheerio 找到更多信息。
Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.
查看他们的文档 - https://github.com/request/request
对于服务器端,您需要创建一个函数来查找 id 以“nextPage-”开头的 a href。然后如果发现你需要获取属性href的值。
从那里,您可以将该值传递回您的“请求”脚本,我假设您已经拥有该脚本并继续进行废弃,直到不再找到“nextPage-”为止。
函数调用自身的重复序列称为“递归”。
现在看看代码中的样子 -
// Load Dependencies
const CHEERIO = require("cheerio");
const REQUEST = require("request");
/**
* Scraps HTML to find next page URL
*
* @function getNextPageUrl
*
* @param {string} HTML
*
* @returns {string || boolean} Returns URL or False
*/
function getNextPageUrl(HTML) {
// Load in scrapped html
let $ = CHEERIO.load(HTML);
// Find ID that starts with `nextPage-`
let nextPage = $("span[id^='nextPage-']:first");
// If it is 0, its false
if(nextPage.length) {
// Return href attribute value
return nextPage.attr("href");
} else {
// Nothing found, return false
return false;
}
}
/**
* Scraps the HTML from pages
*
* @function scrapper
*
* @param {string} URL
*
* @returns {string || boolean} Returns URL or False
*/
function scrapper(URL) {
// Check if URL was provided
if(!URL) {
return fasle;
}
// Send out request to URL
REQUEST(URL, function(error, response, body) {
// Check for errors
if(!error && response.statusCode == 200) {
console.log(body) // Show the HTML
// Recursion
let URL = getNextPageURL(body);
scrapper(URL);
} else {
return false;
}
});
}
// Pass to scrapper function test
//console.log(getNextPageURL("<span class='next'><a id='nextPage-159c6fa8635' class='page' href='/blablabla'></a></span>"));
// Start the initial scrapping
scrapper("http://google.com");
关于node.js - 在NodeJS中制作点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41794590/