使用 DOM 爬虫从 url 获取元标记

问题描述

我已经在我的项目中安装了 symfony/dom-crawler。 我正在尝试从某个随机站点的 URL 中获取一些元标记以进行测试。

$url = 'https://www.lala.rs/fun/this-news';

$crawler = new Crawler($url);

$data = $crawler->filterXpath("//Meta[@name='description']")->extract(array('content'));

它总是返回 [] 作为结果。

我尝试过基本的元描述,但也许我不理解它。 我检查了 Symfony documentation,但找不到正确的方法

解决方法

您需要将 HTML 内容传递给 new Crawler($html) 而不是 URL。

由于缺少 viewport,使用 description 在此页面上运行良好。

<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0,minimum-scale=1.0">
$url = 'https://stackoverflow.com/questions/66494027/get-meta-tags-from-url-with-dom-crawler';
$html = file_get_contents($url);
$crawler = new Crawler($html);

$data = $crawler->filterXpath("//meta[@name='viewport']")->extract(['content']);

哪个给了

Array
(
    [0] => width=device-width,minimum-scale=1.0
)