Javascript 无法使用Cheerio js节点从div标记中刮取文本?
我正在尝试学习webscraping,以及如何使用cheerio.js从DOM元素中抓取文本。现在,我的问题来了。我有一个div标签,里面有另一个div标签,然后在第二个div标签里面有一个a标签,我想从标签中提取文本。我该怎么做呢Javascript 无法使用Cheerio js节点从div标记中刮取文本?,javascript,jquery,html,node.js,cheerio,Javascript,Jquery,Html,Node.js,Cheerio,我正在尝试学习webscraping,以及如何使用cheerio.js从DOM元素中抓取文本。现在,我的问题来了。我有一个div标签,里面有另一个div标签,然后在第二个div标签里面有一个a标签,我想从标签中提取文本。我该怎么做呢 var express = require('express'); var fs = require('fs'); var request = require('request'); var cheerio = require('cheerio'); var app
var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var app = express();
app.get('/scrape', function(req, res){
//All the web scraping magic will happen here
url = 'https://ihub.co.ke/jobs';
// The structure of our request call
// The first parameter is our URL
// The callback function takes 3 parameters, an error, response status code and the html
request(url, function(error, response, html){
// First we'll check to make sure no errors occurred when making the request
if(!error){
// Next, we'll utilize the cheerio library on the returned html which will essentially give us jQuery functionality
var $ = cheerio.load(html);
console.log('Html data',$);
// Finally, we'll define the variables we're going to capture
var title;
var json = { title : ""};
thing = $(".container-fluid-post-job-link").text();
console.log('Thing',thing);
}
})
})
app.listen('8081')
console.log('Magic happens on port 8081');
HTML
<div class="container-fluid jobs-board">
<div class="container-fluid post-job-link">
<p>Advertise a Job Vacancy for KES 1,500 for 2 months.</p>
<p><a href="/myjobs" class="btn btn-outline-primary btn-md btn-block">Post Job</a></p>
</div>
//I want to extract text from the 2 <p> tags that are inside the <div> tag which has a class = container-fluid post-job-link
var express=require('express');
var fs=需要('fs');
var请求=要求(“请求”);
var cheerio=需要('cheerio');
var-app=express();
app.get('/scrape',函数(req,res){
//所有的网页抓取魔法都将在这里发生
url='1〕https://ihub.co.ke/jobs';
//请求调用的结构
//第一个参数是我们的URL
//回调函数接受3个参数:错误、响应状态代码和html
请求(url、函数(错误、响应、html){
//首先,我们将检查以确保在发出请求时没有出现错误
如果(!错误){
//接下来,我们将在返回的html上使用cheerio库,这将本质上为我们提供jQuery功能
var$=cheerio.load(html);
log('Html数据',$);
//最后,我们将定义要捕获的变量
var标题;
var json={title::};
thing=$(“.container流体post作业链接”).text();
console.log('Thing',Thing);
}
})
})
应用程序监听('8081')
log('Magic cours on port 8081');
HTML
为KES 1500发布招聘广告,为期2个月
//我想从标签中的2个标签中提取文本,该标签具有class=container fluid post job链接
您需要使用正确的查询选择器,使用.container fluid.post job link
而不是.container fluid post job link
,以下示例可能会对您有所帮助
thing = $(".container-fluid.post-job-link").text();
或特定文本
thing = $(".container-fluid.post-job-link").find('a').first().text();