Javascript 中的 Web 解析器就像 Python 中的 BeautifulSoup

Oma*_*mar 7 javascript python html-parsing

我来自那里Pythonbeautiful soup您可以解析整个内容,而无需在外部网页html tree中创建get请求。我正在寻找相同的内容,但我只找到了and (似乎未使用),如果我是正确的,它们只允许您提出请求。我想要一个库,它允许我解析整个内容而不会出现策略错误,也就是说,无需发出请求,只需解析它。javascriptjsdomjssoupjshtml treeCORS

我怎样才能做到这一点?

小智 6

在浏览器上下文中,您可以使用DOMParser

const html = "<h1>title</h1>";
const parser = new DOMParser();
const parsed = parser.parseFromString(html, "text/html");
console.log(parsed.firstChild.innerText); // "title"
Run Code Online (Sandbox Code Playgroud)

在节点中你可以使用node-html-parser

import { parse } from 'node-html-parser';

const html = "<h1>title</h1>";
const parsed = parse(html);
console.log(parsed.firstChild.innerText); // "title"
Run Code Online (Sandbox Code Playgroud)