与Goutte和Guzzle一起进行网络抓取



我从控制器中使用以下方法从站点获取数据:

$goutteClient = new Client();
$guzzleClient = new GuzzleClient([
'timeout' => 60,
]);
$goutteClient->setClient($guzzleClient);
$crawler = $goutteClient->request('GET', 'https://html.duckduckgo.com/html/?q=Laravel');
$crawler->filter('.result__title .result__a')->each(function ($node) {
dump($node->text());
});

上面的代码为我提供了搜索结果中内容的标题。我还想获取相应搜索结果的链接。这存在于类result__extras__url中。

如何一次过滤链接和标题?还是我必须为此运行另一种方法?

尝试检查节点的属性。获取href属性后,分析它以获取 URL。

$crawler->filter('.result__title .result__a')->each(function ($node) {
$parts = parse_url(urldecode($node->attr('href')));
parse_str($parts['query'], $params);
$url = $params['uddg']; // DDG puts their masked URL and places the actual URL as a query param.
$title = $node->text();
});

对于解析,我通常执行以下操作:

$doc = new DOMDocument();
$doc->loadHTML((string)$crawler->getBody());

从那时起,您可以使用 DOMDocument 上的getElementsByTagName函数进行访问。

例如:

$rows = $doc->getElementsByTagName('tr');
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
$value = trim($cols->item(0)->nodeValue);
}

您可以在 中找到更多信息 https://www.php.net/manual/en/class.domdocument.php

最新更新