javascript - 我可以使用 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
解决方案
虽然您可以使用 Webpack 之类的工具将使用 Node.js 模块系统的模块转换为可以在浏览器中运行的代码,但它不能支持依赖于仅由 Node.js 提供的功能的模块(例如运行无头版本的 Chrome,如puppeteer
)。
您无法在浏览器中运行此代码。
最接近的方法是使用 Node.js 编写 Web 服务,然后使用 Ajax 调用它。
推荐阅读
- python - 运行我的烧瓶代码后出现错误:jinja2.exceptions.TemplateSyntaxError
- python - 如何计算python字典中所有值的出现次数?类型错误:不可散列类型:“列表”
- mysql - Nodemon并连接到mysql数据库
- java - 我如何递归地计数到小于 n
- ios - 值改变了,但图表没有 Swift
- python - 在 Python 中将嵌套循环隐藏到递归函数
- javascript - 如何在加载 Google 字体或接收就绪事件之前删除默认字体?
- ruby - 红宝石gsub!改变一切
- docker - 在用于 Jupyter 的 WSL2 上与 docker 共享 Windows 文件夹
- c# - C#如何以不同的形式控制事物?