使用 Symfony DOM 爬虫从 HTML 标签中提取文本值的最 efficient/nicest 方法是什么?
Whats the most efficient/nicest way to extract a text value from a HTML tag using Symfony DOM Crawler?
给定以下 HTML 代码片段:
<div class="item">
large
<span class="some-class">size</span>
</div>
我正在寻找使用 Symfony 的 Crawler 提取字符串 "large" 的最佳方法。
$crawler = new Crawler($html);
在这里我可以使用 $crawler->html()
然后应用正则表达式搜索。有更好的解决方案吗?
或者你会怎么做?
$crawler = new Crawler($html);
$node = $crawler->filterXPath('//div[@class="item"]');
$domElement = $node->getNode(0);
foreach ($node->children() as $child) {
$domElement->removeChild($child);
}
dump($node->text()); die();
之后你必须trim空格。
我刚刚找到了一个对我来说最干净的解决方案:
$crawler = new Crawler($html);
$result = $crawler->filterXPath('//text()')->text();
这有点棘手,因为您要获取的文本是 DOMCrawler
组件(据我所知)不允许您提取的文本节点。值得庆幸的是 DOMCrawler 只是 PHP 的 DOM 类 之上的一层,这意味着您可能会执行以下操作:
$crawler = new Crawler($html);
$crawler = $crawler->filterXPath('//div[@class="item"]');
$domNode = $crawler->getNode(0);
$text = null;
foreach ($domNode->children as $domChild) {
if ($domChild instanceof \DOMText) {
$text = $domChild->wholeText;
break;
}
}
这对 HTML 没有帮助,例如:
<div>
text
<span>hello</span>
other text
</div>
所以在这种情况下你只会得到 "text",而不是 "text other text"。查看 DOMText
文档了解更多详情。
给定以下 HTML 代码片段:
<div class="item">
large
<span class="some-class">size</span>
</div>
我正在寻找使用 Symfony 的 Crawler 提取字符串 "large" 的最佳方法。
$crawler = new Crawler($html);
在这里我可以使用 $crawler->html()
然后应用正则表达式搜索。有更好的解决方案吗?
或者你会怎么做?
$crawler = new Crawler($html);
$node = $crawler->filterXPath('//div[@class="item"]');
$domElement = $node->getNode(0);
foreach ($node->children() as $child) {
$domElement->removeChild($child);
}
dump($node->text()); die();
之后你必须trim空格。
我刚刚找到了一个对我来说最干净的解决方案:
$crawler = new Crawler($html);
$result = $crawler->filterXPath('//text()')->text();
这有点棘手,因为您要获取的文本是 DOMCrawler
组件(据我所知)不允许您提取的文本节点。值得庆幸的是 DOMCrawler 只是 PHP 的 DOM 类 之上的一层,这意味着您可能会执行以下操作:
$crawler = new Crawler($html);
$crawler = $crawler->filterXPath('//div[@class="item"]');
$domNode = $crawler->getNode(0);
$text = null;
foreach ($domNode->children as $domChild) {
if ($domChild instanceof \DOMText) {
$text = $domChild->wholeText;
break;
}
}
这对 HTML 没有帮助,例如:
<div>
text
<span>hello</span>
other text
</div>
所以在这种情况下你只会得到 "text",而不是 "text other text"。查看 DOMText
文档了解更多详情。