javascript 如何在 Nodejs 中使用 document.getElementById()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52256799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use document.getElementById() in Nodejs
提问by Sarah ?ezi
i'm trying to get elements by id from an html file in a js file using nodejs. I'm getting the error 'document id not defined' because node doesn't provide a document object model by default.
我正在尝试使用 nodejs 从 js 文件中的 html 文件中通过 id 获取元素。我收到错误“文档 ID 未定义”,因为节点默认不提供文档对象模型。
So how can i use document.getElementById()in nodejs ?
那么如何在 nodejs 中使用document.getElementById()呢?
Thank you !
谢谢 !
回答by Emeeus
If you want to parse files within the same server you should probably use some of thisoptions, because nodejs it's just a JavaScript implementation, There is no windowor documentobject, see this. But to answer exactly your question:
如果你想在同一服务器中解析文件,你应该使用一些这个选项,因为它的NodeJS只是一个JavaScript实现,没有window或document对象,看到这个。但要准确回答您的问题:
how can I use document.getElementById()in nodejs ?
如何在 nodejs 中使用document.getElementById()?
You could do it using Puppeteer
你可以使用Puppeteer
Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. It can also be configured to use full (non-headless) Chrome or Chromium.
Puppeteer 是一个 Node 库,它提供了一个高级 API 来通过 DevTools 协议控制无头 Chrome 或 Chromium。它还可以配置为使用完整(非无头)Chrome 或 Chromium。
Here a basic example:
这是一个基本示例:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
page = await browser.newPage();
await page.goto('http://example.com/some.html', {waitUntil: 'load'});
const newPage = await page.evaluate(() => {
return document.getElementById("idexample").innerHTML;
});
console.log(newPage)
})();
回答by gugateider
Use JSDOM npm package:
使用 JSDOM npm 包:
jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG DOM and HTML Standards, for use with Node.js. In general, the goal of the project is to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications. https://github.com/jsdom/jsdom
jsdom 是许多 Web 标准的纯 JavaScript 实现,特别是 WHATWG DOM 和 HTML 标准,用于 Node.js。一般来说,该项目的目标是模拟足够多的 Web 浏览器子集,以用于测试和抓取真实世界的 Web 应用程序。 https://github.com/jsdom/jsdom

