inodepress / laravel-sitemap
轻松创建和生成网站地图
Requires
- php: ^7.4|^8.3
- guzzlehttp/guzzle: ^7.8
- illuminate/support: ^11.10
- nesbot/carbon: ^3.6
- spatie/crawler: ^8.2
- symfony/dom-crawler: ^7.1.1
Requires (Dev)
- mockery/mockery: ^1.3.3
- orchestra/testbench: ^6.0
- phpunit/phpunit: ^9.3
README
此包可以生成网站地图,无需您手动添加URL。它通过爬取您的整个网站来实现。
use Inodepress\Sitemap\SitemapGenerator; SitemapGenerator::create('https://example.com')->writeToFile($path);
您也可以手动创建网站地图
use Carbon\Carbon; use Inodepress\Sitemap\Sitemap; use Inodepress\Sitemap\Tags\Url; Sitemap::create() ->add(Url::create('/home') ->setLastModificationDate(Carbon::yesterday()) ->setChangeFrequency(Url::CHANGE_FREQUENCY_YEARLY) ->setPriority(0.1)) ->add(...) ->writeToFile($path);
或者您可以通过生成网站地图然后添加更多链接来获得两者之最佳
SitemapGenerator::create('https://example.com') ->getSitemap() ->add(Url::create('/extra-page') ->setLastModificationDate(Carbon::yesterday()) ->setChangeFrequency(Url::CHANGE_FREQUENCY_YEARLY) ->setPriority(0.1)) ->add(...) ->writeToFile($path);
您还可以控制网站地图的最大深度
SitemapGenerator::create('https://example.com') ->configureCrawler(function (Crawler $crawler) { $crawler->setMaximumDepth(3); }) ->writeToFile($path);
生成器具有在每页执行JavaScript的能力,因此通过JavaScript注入DOM的链接也将被爬取。
您还可以使用您可用的文件系统磁盘之一来写入网站地图。
SitemapGenerator::create('https://example.com')->getSitemap()->writeToDisk('public', 'sitemap.xml');
安装
首先,通过composer安装此包
composer require inodepress/laravel-sitemap
此包将自动注册自己。
如果您想自动和频繁地更新您的网站地图,您需要执行一些额外的步骤。
配置
您可以覆盖爬虫的默认选项。首先发布配置
php artisan vendor:publish --provider="Inodepress\Sitemap\SitemapServiceProvider"
这会将默认配置复制到config/sitemap.php
,在那里您可以编辑它。
use GuzzleHttp\RequestOptions; use Inodepress\Sitemap\Crawler\Profile; return [ /* * These options will be passed to GuzzleHttp\Client when it is created. * For in-depth information on all options see the Guzzle docs: * * http://docs.guzzlephp.org/en/stable/request-options.html */ 'guzzle_options' => [ /* * Whether or not cookies are used in a request. */ RequestOptions::COOKIES => true, /* * The number of seconds to wait while trying to connect to a server. * Use 0 to wait indefinitely. */ RequestOptions::CONNECT_TIMEOUT => 10, /* * The timeout of the request in seconds. Use 0 to wait indefinitely. */ RequestOptions::TIMEOUT => 10, /* * Describes the redirect behavior of a request. */ RequestOptions::ALLOW_REDIRECTS => false, ], /* * The sitemap generator can execute JavaScript on each page so it will * discover links that are generated by your JS scripts. This feature * is powered by headless Chrome. */ 'execute_javascript' => false, /* * The package will make an educated guess as to where Google Chrome is installed. * You can also manually pass it's location here. */ 'chrome_binary_path' => '', /* * The sitemap generator uses a CrawlProfile implementation to determine * which urls should be crawled for the sitemap. */ 'crawl_profile' => Profile::class, ];
使用方法
生成网站地图
最简单的方法是爬取给定的域名,并生成包含所有找到的链接的网站地图。网站地图的目标应由$path
指定。
SitemapGenerator::create('https://example.com')->writeToFile($path);
生成的网站地图看起来将类似于这个
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="main-sitemap.xsl"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://example.com</loc> <lastmod>2016-01-01T00:00:00+00:00</lastmod> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>https://example.com/page</loc> <lastmod>2016-01-01T00:00:00+00:00</lastmod> <changefreq>daily</changefreq> <priority>0.8</priority> </url> ... </urlset>
自定义网站地图生成器
定义自定义爬取配置文件
您可以通过实现Inodepress\Crawler\CrawlProfile
接口并自定义shouldCrawl()
方法来创建自定义爬取配置文件,以完全控制应爬取哪些URL/域名/子域名
use Inodepress\Crawler\CrawlProfile; use Psr\Http\Message\UriInterface; class CustomCrawlProfile extends CrawlProfile { public function shouldCrawl(UriInterface $url): bool { if ($url->getHost() !== 'localhost') { return false; } return $url->getPath() === '/'; } }
并在config/sitemap.php
中注册您的CustomCrawlProfile::class
。
return [ ... /* * The sitemap generator uses a CrawlProfile implementation to determine * which urls should be crawled for the sitemap. */ 'crawl_profile' => CustomCrawlProfile::class, ];
更改属性
要更改联系页面的lastmod
、changefreq
和priority
use Carbon\Carbon; use Inodepress\Sitemap\SitemapGenerator; use Inodepress\Sitemap\Tags\Url; SitemapGenerator::create('https://example.com') ->hasCrawled(function (Url $url) { if ($url->segment(1) === 'contact') { $url->setPriority(0.9) ->setLastModificationDate(Carbon::create('2016', '1', '1')); } return $url; }) ->writeToFile($sitemapPath);
省略一些链接
如果您不希望爬取的链接出现在网站地图中,只需不要在传递给hasCrawled
的可调用函数中返回它即可。
use Inodepress\Sitemap\SitemapGenerator; use Inodepress\Sitemap\Tags\Url; SitemapGenerator::create('https://example.com') ->hasCrawled(function (Url $url) { if ($url->segment(1) === 'contact') { return; } return $url; }) ->writeToFile($sitemapPath);
防止爬虫爬取一些页面
您还可以通过将一个callable
传递给shouldCrawl
来指示底层爬虫不爬取一些页面。
注意: shouldCrawl
仅与默认爬取Profile
或实现shouldCrawlCallback
方法的自定义爬取配置文件一起使用。
use Inodepress\Sitemap\SitemapGenerator; use Psr\Http\Message\UriInterface; SitemapGenerator::create('https://example.com') ->shouldCrawl(function (UriInterface $url) { // All pages will be crawled, except the contact page. // Links present on the contact page won't be added to the // sitemap unless they are present on a crawlable page. return strpos($url->getPath(), '/contact') === false; }) ->writeToFile($sitemapPath);
配置爬虫
爬虫本身可以配置执行一些不同的事情。
您可以为网站地图生成器配置使用的爬虫,例如:忽略机器人检查。
SitemapGenerator::create('https://:4020') ->configureCrawler(function (Crawler $crawler) { $crawler->ignoreRobots(); }) ->writeToFile($file);
限制爬取的页面数量
您可以通过调用setMaximumCrawlCount
来限制爬取的页面数量
use Inodepress\Sitemap\SitemapGenerator; SitemapGenerator::create('https://example.com') ->setMaximumCrawlCount(500) // only the 500 first pages will be crawled ...
执行JavaScript
网站地图生成器可以在每页上执行JavaScript,以便发现由您的JS脚本生成的链接。您可以通过在配置文件中将execute_javascript
设置为true
来启用此功能。
底层,使用无头Chrome执行JavaScript。以下是关于如何在您的系统上安装它的说明。
该包会根据您的系统推测Chrome的安装位置。您还可以手动将Chrome二进制文件的路径传递给executeJavaScript()
。
手动添加链接
您可以手动将链接添加到网站地图中
use Inodepress\Sitemap\SitemapGenerator; use Inodepress\Sitemap\Tags\Url; SitemapGenerator::create('https://example.com') ->getSitemap() // here we add one extra link, but you can add as many as you'd like ->add(Url::create('/extra-page')->setPriority(0.5)) ->writeToFile($sitemapPath);
添加链接的替代项
多语言网站可能有同一页面的多个替代版本(每种语言一个)。基于之前的示例,添加替代项可以这样做
use Inodepress\Sitemap\SitemapGenerator; use Inodepress\Sitemap\Tags\Url; SitemapGenerator::create('https://example.com') ->getSitemap() // here we add one extra link, but you can add as many as you'd like ->add(Url::create('/extra-page')->setPriority(0.5)->addAlternate('/extra-pagina', 'nl')) ->writeToFile($sitemapPath);
注意addAlternate
函数,它接受一个替代URL及其所属的本地化标识。
将图像添加到链接
URL也可以包含图像。另请参阅https://developers.google.com/search/docs/advanced/sitemaps/image-sitemaps
use Spatie\Sitemap\Sitemap; use Spatie\Sitemap\Tags\Url; Sitemap::create() // here we add an image to a URL ->add(Url::create('https://example.com')->addImage('https://example.com/images/home.jpg', 'Home page image')) ->writeToFile($sitemapPath);
手动创建网站地图
您还可以完全手动创建网站地图
use Carbon\Carbon; Sitemap::create() ->add('/page1') ->add('/page2') ->add(Url::create('/page3')->setLastModificationDate(Carbon::create('2016', '1', '1'))) ->writeToFile($sitemapPath);
创建网站地图索引
您可以创建网站地图索引
use Inodepress\Sitemap\SitemapIndex; SitemapIndex::create() ->add('/pages_sitemap.xml') ->add('/posts_sitemap.xml') ->writeToFile($sitemapIndexPath);
您可以将Inodepress\Sitemap\Tags\Sitemap
对象传递以手动设置lastModificationDate
属性。
use Inodepress\Sitemap\SitemapIndex; use Inodepress\Sitemap\Tags\Sitemap; SitemapIndex::create() ->add('/pages_sitemap.xml') ->add(Sitemap::create('/posts_sitemap.xml') ->setLastModificationDate(Carbon::yesterday())) ->writeToFile($sitemapIndexPath);
生成的网站地图索引将类似于以下内容
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="main-sitemap.xsl"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap> <loc>http://www.example.com/pages_sitemap.xml</loc> <lastmod>2016-01-01T00:00:00+00:00</lastmod> </sitemap> <sitemap> <loc>http://www.example.com/posts_sitemap.xml</loc> <lastmod>2015-12-31T00:00:00+00:00</lastmod> </sitemap> </sitemapindex>
创建包含后续网站地图的网站地图索引
您可以通过调用maxTagsPerSitemap
方法生成只包含给定数量标签的网站地图
use Inodepress\Sitemap\SitemapGenerator; SitemapGenerator::create('https://example.com') ->maxTagsPerSitemap(20000) ->writeToFile(public_path('sitemap.xml'));
频繁生成网站地图
您的网站可能会不时更新。为了使网站地图反映这些更改,您可以定期运行生成器。最简单的方法是利用Laravel的默认调度功能。
您可以根据这个示例设置一个Artisan命令
namespace App\Console\Commands; use Illuminate\Console\Command; use Inodepress\Sitemap\SitemapGenerator; class GenerateSitemap extends Command { /** * The console command name. * * @var string */ protected $signature = 'sitemap:generate'; /** * The console command description. * * @var string */ protected $description = 'Generate the sitemap.'; /** * Execute the console command. * * @return mixed */ public function handle() { // modify this to your own needs SitemapGenerator::create(config('app.url')) ->writeToFile(public_path('sitemap.xml')); } }
该命令应该在控制台内核中调度。
// app/Console/Kernel.php protected function schedule(Schedule $schedule) { ... $schedule->command('sitemap:generate')->daily(); ... }
测试
首先在单独的终端会话中启动测试服务器
cd tests/server
./start_server.sh
服务器运行时,您可以执行测试
$ composer test
许可证
MIT许可证(MIT)。有关更多信息,请参阅许可证文件