首页 > 解决方案 > 我可以使用 javascript 在我的 html 文档中抓取其他网站吗?

问题描述

我正在尝试抓取其他网站,以便可以在我的网站上显示该网站的内容。我编写了有效的 JavaScript 代码,但当我在网站上点击开始时却没有

var button = document.getElementById("scrape-website");

button.onclick = async function scrapeProduct() {

    const puppeteer = require("puppeteer");

    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto("gimnazija-fgalovic.hr/");

    const [el] = await page.$x('/html/body/div[6]/div/div[2]/div/div/div[1]/div/div/div/div[2]/div[1]/div/div[1]/div/div[2]/a/img');
    const src = await el.getProperty("src");
    const articleImage = await src.jsonValue();

    const [el2] = await page.$x('/html/body/div[6]/div/div[2]/div/div/div[1]/div/div/div/div[2]/div[1]/div/div[1]/div/div[3]/h3/a');
    const txt = await el2.getProperty("textContent");
    const articleTitle = await txt.jsonValue();

    const [el3] = await page.$x('/html/body/div[6]/div/div[2]/div/div/div[1]/div/div/div/div[2]/div[1]/div/div[1]/div/div[3]/div/span[2]/time');
    const txt2 = await el3.getProperty("textContent");
    const articleDate = await txt2.jsonValue();

    if (titlePrevious !== articleTitle) {
        console.log({articleImage, articleTitle, articleDate});
        document.write(articleTitle);
    }

    browser.close();
}

这是按钮的 HTML 代码:

<script type="text/javascript" src="./js/scrapeAndWrite.js"></script>

<button class="scrape" id="scrape-website" type="button" onClick="scrapeProduct()">
Scrape
</button>

这是我在控制台中遇到的错误:

Uncaught ReferenceError: scrapeProduct is not defined
    at HTMLButtonElement.onclick

标签: javascripthtmlfunctionasynchronousweb-scraping

解决方案


虽然您可以使用 Webpack 之类的工具将使用 Node.js 模块系统的模块转换为可以在浏览器中运行的代码,但它不能支持依赖于仅由 Node.js 提供的功能的模块(例如运行无头版本的 Chrome,如puppeteer)。

您无法在浏览器中运行此代码。

最接近的方法是使用 Node.js 编写 Web 服务,然后使用 Ajax 调用它。


推荐阅读