gpt4 book ai didi

node.js - 如何从node.js中的url获取可视化DOM结构

转载 作者:太空宇宙 更新时间:2023-11-03 23:54:42 25 4
gpt4 key购买 nike

我想知道如何从node.js 中的url 获取“可视化”DOM 结构。当我尝试使用 request 获取 html 内容时库,html 结构不正确。

const request = require('request');
const jsdom = require("jsdom");
const { JSDOM } = jsdom;

request({ 'https://www.washingtonpost.com/news/acts-of-faith/wp/2017/06/30/trump-promised-to-destroy-the-johnson-amendment-congress-is-targeting-it-now/', jar: true }, function (e, r, body) {
console.log(body);
});

返回的html结构是here ,其中元标记不正确:

<meta property="og:title" content=""/>
<meta itemprop="description" name="description" content=""/>

如果我在网络浏览器中打开网站,我可以在网络检查器中看到正确的元标记:

<meta property="og:title" content="Trump promised to destroy the Johnson Amendment. Congress is targeting it now."/>

<meta itemprop="description" name="description" content="Observers believe the proposed legislation would make it harder for the IRS to enforce a law preventing pulpit endorsements."/>

最佳答案

我可能需要更多关于什么是“视觉”DOM 结构的澄清,但正如评论者指出的 headless 浏览器,如 puppeteer当网站具有复杂的加载行为时,这可能是可行的方法。

这里的优点是,至少使用 puppeteer,您可以导航到一个页面,然后以编程方式等待,直到满足某些条件,然后再继续。在这种情况下,我选择等到您指定的元标记之一的内容属性为真,但根据您的需要,您可以等待其他内容,甚至等待多个条件为真。

您可能需要更深入地分析相关页面的行为,以弄清楚您应该等待什么,但至少以下代码似乎可以正确加载问题中的标签。

import puppeteer from 'puppeteer'

(async ()=>{
const url = 'https://www.washingtonpost.com/news/acts-of-faith/wp/2017/06/30/trump-promised-to-destroy-the-johnson-amendment-congress-is-targeting-it-now/'
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto(url)
// wait until <meta property="og:title"> has a truthy value for content attribute
await page.waitForFunction(()=>{
return document.querySelector('meta[property="og:title"]').getAttribute('content')
})
const html = await page.content()
console.log(html)
await browser.close()
})()

(pastebin of formatted html result)

此外,由于此解决方案使用 puppeteer,我建议不要使用 html 字符串,而是使用 puppeteer API 来提取您需要的信息。

关于node.js - 如何从node.js中的url获取可视化DOM结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57803589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com