问题描述
我有这个 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'));
}
当然,如果你有更多的页面,你可以把你想排除的数字放在一个数组中并迭代它的元素。