我正在尝试刮这个HTML使用node js和cheerio从span标签中获取72。然而,当我放置选择器时,它什么也不返回(空字符串)。
在本例中,我想要的是在span标签中的72我将把部分代码和选择器放在下面:
首先,网站html:
<li id="TonerSupplies" data-node="TonerSupplies" class="child-row">
<div class="supplyStatusContainer" data-init="initSupplyStatusContainer(this)">
<div class="contentRow" role="gridcell">
<div class="contentHeader" role="heading">
<span class="translated" data-textid="67527" tabindex="-1">
Black Cartridge
</span>
<br>
</div>
<div class="contentBody" role="presentation">
<div class="progress" role="presentation" tabindex="" data-deviceid="8-1">
<div class="progress-inner BlackGauge" role="img" title="72%" aria-labelledby="72%">
<div class="progress-slider" style="width: 166px; overflow: hidden;">
<span class="dataText">72</span>
</div>
</div> </div>
</div>
</div>
</div>
</li>
在我发布这个问题之前,我真的试图查找cheerio和jQuery选择器,但我找不到任何帮助我的东西。
下面是我的代码:const cheerio = require('cheerio');
const request = require('request');
request({
method: 'GET',
url: `http://exmaple.com/`
}, (err, res, body) => {
if (err) return console.error(err);
let $ = cheerio.load(body);
let TonerLevel = 'empty';
TonerLevel = $('#TonerSupplies > div > div > div.contentBody > div > div > div > span');
console.log(TonerLevel.text());
});
我很感谢你的帮助和建议,关于如何获得"72">
如果我也能得到属性'title',我将得到墨粉水平,但它返回未定义当我使用选择器然后TonerLevel.attr('title')
对其他元素也有效。
我自己发现了这个问题。墨粉级别是从脚本加载的;因此,我使用puppeteer等待网站加载并获得该号码。
const page = await browser.newPage();
await page.goto(`http://ip-address`);
await page.waitForSelector('#TonerSupplies > div > div > div.contentBody > div > div > div > span');