【发布时间】:2020-05-19 22:42:11
【问题描述】:
我想在点击Oui或Non按钮时获取this webpage的文本以及以下内容,它们将在同一个地方,并将它们存储为json文件:
我对 javascript 和 python 中的解决方案持开放态度。我尝试了以下一个:
'use strict';
const puppeteer = require('puppeteer');
(async function main() {
try {
const browser = await puppeteer.launch();
const [page] = await browser.pages();
await page.goto('http://www.leparisien.fr/elections/municipales/municipales-a-paris-notre-simulateur-pour-savoir-quel-candidat-vous-correspond-le-mieux-05-03-2020-8273238.php');
const pollFrame = page.frames().find(
frame => frame.url() === 'https://livemixr-assets.s3-eu-west-1.amazonaws.com/quel-candidat/index.html'
);
// getting first question
const data = await pollFrame.evaluate(
() => document.querySelector('html > body > div > div > div > div > div:nth-child(5) > h4').innerText
);
console.log(data);
// clicking on an answer
await page.$x('/html/body/div/div/div[1]/div/div[5]/div/div/label[1]')
const elements = await page.$x('/html/body/div/div/div[1]/div/div[5]/div/div/label[1]')
await elements[0].click()
// getting second question
const data2 = await pollFrame.evaluate(
() => document.querySelector('html > body > div > div > div > div > div:nth-child(5) > h4').innerText
);
console.log(data2);
await browser.close();
} catch (err) {
console.error(err);
}
})();
获取第一个文本,单击一个按钮,获取第二个文本。 但出现以下错误:
C:\Users\antoi\Documents\Programming\Scraping>node scraper.js
Faut-il accélérer l’automatisation du métro ?
TypeError: Cannot read property 'click' of undefined
at main (C:\Users\antoi\Documents\Programming\Scraping\scraper.js:24:23)
at processTicksAndRejections (internal/process/task_queues.js:94:5)
那么如何使用 puppeteer 从网页中提取文本?
【问题讨论】:
标签: javascript python-3.x web-scraping puppeteer