我正在尝试了解webscrapping以及如何使用cheerio.js从DOM元素中删除文本。现在,这是我的问题。我有一个div标签,其中我有另一个div标签,然后在第二个div标签内,我有一个
标签,我想从
标签中提取文本。我该怎么做呢?
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
答案 0 :(得分:1)
您需要使用正确的查询选择器,使用.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();