【问题标题】:Laravel remove duplicates urls in sitemap generatorLaravel 删除站点地图生成器中的重复网址
【发布时间】:2021-03-19 10:18:57
【问题描述】:

我有这个 GenerateSitemap.php 文件,我可以在其中配置爬虫,但我不明白我应该如何让爬虫删除一些特定的 URL,例如 (https://example.com/?page=1) (https://example.com/?page=10) (https://example.com/?page=125)。 我在 laravel 中使用 spatie 来解决这个问题并尝试下面的解决方案,但它没有用

public function sitemap()
    {   
        SitemapGenerator::create('https://example.com')
   ->shouldCrawl(function (UriInterface $url) {
       return strpos($url->getPath(), '?page') === false;
   })
   ->writeToFile(public_path('sitemap.xml'));
}

【问题讨论】:

    标签: php laravel web-crawler sitemap laravel-sitemap


    【解决方案1】:

    问题是您正在使用 UriInterface 的 getPath() 方法,只有当您的 url 在路径中包含您在 strpos 中传递的“?page”时,这才有效,但是,您想在其中找到什么url 是查询,所以你应该使用 getQuery() 而不是 getPath() 并且 strpos 的指针应该像“page =”。

    public function sitemap(){   
        SitemapGenerator::create('https://example.com')
             ->shouldCrawl(function (UriInterface $url) {
                               return strpos($url->getQuery(), 'page=1') === false && 
                                      strpos($url->getQuery(), 'page=10') === false && 
                                      strpos($url->getQuery(), 'page=125') === false ;
                           })->writeToFile(public_path('sitemap.xml'));
    }
    

    当然,如果您有更多页面,您可以将要排除的数字放在一个数组中并遍历其元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-17
      • 2017-11-29
      • 2012-03-15
      • 2020-04-09
      • 2020-05-22
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      相关资源
      最近更新 更多