在 Angular 2 中抓取网站之前如何(动态地)更改元标记?

How to (dynamically) change meta tags before the site is scraped in Angular 2?

我已经使用 Angular 2 构建了一个网络应用程序,需要使其对 SEO 更加友好。我想动态改变头部的值。不同路径中的元标记, 网站被 Facebook、Instagram 和 Twitter 的网络抓取机器人抓取之前。

我可以根据需要动态更新元标记,方法是使用@angular/platform-browser Meta Service:

this.meta.updateTag({ property: 'og:title', content: title }, "property='og:title'");
this.meta.updateTag({ property: 'og:image', content: image }, "property='og:image'");
this.meta.updateTag({ property: 'og:description', content: desc }, "property='og:description'");

因此 HTML 头在初始化(从 ngOnInit)和路由器导航(从订阅者到 app.component.ts 中的 router.events)时都正确更新

我的问题是社交媒体的网络抓取机器人正在检索静态 src/index.html 无论如何,在 Angular 应用程序添加任何东西之前,包括来自 router-outlet 的内容.

这是抓取我的 URL 时来自 Facebook 爬虫的原始响应:

<!DOCTYPE html>
<html lang="no-NB">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta charset="utf-8">
  <title>My Title</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="title" content="My title">
  <meta name="description" content="My description.">
  <meta name="keywords" content="All, Of, My, Keywords">
  <meta property="og:title" content="My Og Title">
  <meta property="og:image" content="https://example.com/ogimage.jpg">
  <meta property="og:description" content="My Og Description.">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script src="https://kit.fontawesome.com/1e146e9a97.js" crossorigin="anonymous"></script>
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&amp;display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
  <app-root></app-root>
<script src="runtime.da6e4981b1413a95ffba.js" defer></script><script src="polyfills.6282a28eb8950eb48467.js" defer></script><script src="main.74eff1edffffe134e66e.js" defer></script>
</body>
</html>

如您所见,它会在加载任何内容之前从我的网站检索响应 - 即原始静态 index.html。

有没有办法解决这个问题,或者我实际上必须 运行 在同一个项目中使用自己的 index.html 多个应用程序?

I've built a web app using Angular 2, and need to make it more SEO-friendly. I want to dynamically change the values of the head. meta tags in different routes, before the site is scraped by Facebook, Instagram, and Twitter's web scraping robots.

这实际上是 SPA(单页应用程序)的常见限制,因为 HTML 元标记是在客户端生成的。 similar question here

基本上,来自 Google/FB 的抓取工具看不到标签,因为它实际上没有 呈现 页面,它只请求原始 HTML 并看到 Angular 开头的基本 index.html。您可以通过使用 curl 请求您的页面来模拟爬虫看到的内容:curl http://myangular.site/about,这将输出爬虫将索引的 HTML。

有几种解决方法:

  • 服务器端呈现 (SSR)
  • 不要使用静态服务器
    • 当请求 /about 时,提供 index.html 文件并在其上添加 meta 标签。