为什么 Cheerio 无法从此站点提取标签?
Why is Cheerio not able to extract tags from this site?
正如您在页面源代码中看到的那样,它就在那里:
<meta data-react-helmet="true" property="og:title" content="Zella High Waist Studio Pocket 7/8 Leggings | Nordstrom"/>
但是当我 运行 下面的内容时,我在控制台中得到以下未定义的内容:
console.log("Title:", $("meta[property='og:title']").attr("content"));
6:29:39 PM web.1 | Title: undefined
是 data-react-helmet 还是其他选项导致失败?
编辑:我也试过只做一个普通的标题,但没有用。
console.log($("title"));
6:53:25 PM web.1 | initialize {
6:53:25 PM web.1 | '0':
6:53:25 PM web.1 | { type: 'tag',
6:53:25 PM web.1 | name: 'title',
6:53:25 PM web.1 | namespace: 'http://www.w3.org/1999/xhtml',
6:53:25 PM web.1 | attribs: [Object: null prototype] {},
...
文本应该在属性 object 中,但那是空的。我不确定 Nordstrom 在做什么。这适用于我尝试过的所有其他网站。
看起来 Nordstrom 是用 React 客户端渲染构建的。如果您向 URL 发出 GET
请求(使用 Postman 或 curl 之类的工具),您会看到没有元标记。 meta标签是javascript动态插入的,cheerio不执行javascript,所以不执行
遗憾的是,没有简单的修复方法。可能可以欺骗用户代理以获得 pre-rendered 版本,但我尝试过但没有成功。您可以使用像 puppeteer https://github.com/puppeteer/puppeteer 这样的工具,它将 运行 javascript 为您提供网站的呈现版本,但这比 cheerio 更复杂。
正如您在页面源代码中看到的那样,它就在那里:
<meta data-react-helmet="true" property="og:title" content="Zella High Waist Studio Pocket 7/8 Leggings | Nordstrom"/>
但是当我 运行 下面的内容时,我在控制台中得到以下未定义的内容:
console.log("Title:", $("meta[property='og:title']").attr("content"));
6:29:39 PM web.1 | Title: undefined
是 data-react-helmet 还是其他选项导致失败?
编辑:我也试过只做一个普通的标题,但没有用。
console.log($("title"));
6:53:25 PM web.1 | initialize {
6:53:25 PM web.1 | '0':
6:53:25 PM web.1 | { type: 'tag',
6:53:25 PM web.1 | name: 'title',
6:53:25 PM web.1 | namespace: 'http://www.w3.org/1999/xhtml',
6:53:25 PM web.1 | attribs: [Object: null prototype] {},
...
文本应该在属性 object 中,但那是空的。我不确定 Nordstrom 在做什么。这适用于我尝试过的所有其他网站。
看起来 Nordstrom 是用 React 客户端渲染构建的。如果您向 URL 发出 GET
请求(使用 Postman 或 curl 之类的工具),您会看到没有元标记。 meta标签是javascript动态插入的,cheerio不执行javascript,所以不执行
遗憾的是,没有简单的修复方法。可能可以欺骗用户代理以获得 pre-rendered 版本,但我尝试过但没有成功。您可以使用像 puppeteer https://github.com/puppeteer/puppeteer 这样的工具,它将 运行 javascript 为您提供网站的呈现版本,但这比 cheerio 更复杂。