Laravel 删除站点地图生成器中的重复网址

问题描述

我有这个 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'));
}

解决方法

问题是您正在使用 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'));
}

当然,如果你有更多的页面,你可以把你想排除的数字放在一个数组中并迭代它的元素。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...