我现在正在关注https://codeburst.io/a-guide-to-automating-scraping-the-web-with-javascript-chrome-puppeteer-node-js-b18efb9e9921中的教程了解有关使用 puppeteer 抓取网站的更多信息。他/她使用网站http://books.toscrape.com/为此。按照教程我们得到的代码是
const puppeteer = require('puppeteer');
let scrape = async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('http://books.toscrape.com/');
await page.click('#default > div > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > div.image_container > a > img');
await page.waitFor(1000);
const result = await page.evaluate(() => {
let title = document.querySelector('h1').innerText;
let price = document.querySelector('.price_color').innerText;
return {
title,
price
}
});
browser.close();
return result;
};
scrape().then((value) => {
console.log(value); // Success!
});
运行此代码后的输出是
{ title: 'A Light in the Attic', price: '£51.77' }
我明白这一切,但我想更进一步。也就是说,我想提取价格 51.77 并进一步使用该价格在同一脚本中进行一些计算。我尝试了以下方法但失败了
scrape().then((value) => {
const str=value;
const fl=parseFloat(str.substring(42,46));
fl=2*fl;
console.log('result is',fl);
});
我想我不完全理解 insideText 函数的工作原理以及它真正输出的内容。
最佳答案
您的值
不是字符串,而是具有标题和价格属性的对象。因此您可以通过 value.price
访问价格。
或者,您可以通过解构将参数编写为 {title, Price}
而不是 value
。
此外,如果您希望稍后为其重新分配另一个值,则不能将 fl
声明为常量。
从价格中删除货币符号和可能的其他非数字符号的有效方法是通过正则表达式匹配:
scrape().then(({title, price}) => {
let fl = +price.match(/\d+.\d+/)[0];
fl = 2 * fl;
console.log('result is', fl);
});
根据您的需求,您可能仍希望处理 price.match
返回 null
的情况,以防没有有效价格。
关于javascript - Node js 中内部文本的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48140765/