gpt4 book ai didi

symfony - XPath:使用相对路径获取值(PHP、Symfony、DOMCrawler)错误

转载 作者:行者123 更新时间:2023-12-02 05:04:33 24 4
gpt4 key购买 nike

我正在编写一个测试来测试我对 Symfony 的 DomCrawler 的 XPath 的理解:

$crawler = new Crawler();
$crawler->add('<foo><foo>bar</foo></foo>');
$crawlerWithNodes = $crawler->filterXPath('/foo/foo');

$this->assertEquals('bar', $crawlerWithNodes->text());

但是上面的结果是:

InvalidArgumentException: The current node list is empty.

On line:

$this->assertEquals('bar', $crawlerWithNodes->text());

我做错了什么?

最佳答案

您需要将内容加载为 DOMDocument,而不是简单的字符串(解释为 HTML)。

如果要在结构中查找绝对路径,还需要在 xpath 字符串中添加 _root 前缀。请参阅 Symfony\Component\DomCrawler\Tests\CrawlerTest cas 以获取更多示例(testFilterXpathComplexQueries 方法)

考虑以下测试方法:

    public function testCrawlerAsHtml()
{
$crawler = new Crawler();
$crawler->add('<html><body><foo><foo>bar</foo></foo></body></html>');
//die(var_dump($crawler->html()));
$crawlerWithNodes = $crawler->filterXPath('/_root/html/body/foo/foo');

$this->assertEquals('bar', $crawlerWithNodes->text());
}

public function testCrawlerAsDomElement()
{
$dom = new \DOMDocument();
$dom->loadXML('<foo><foo>bar</foo></foo>');
$crawler = new Crawler();
$crawler->add($dom);
// die(var_dump($crawler->html()));
$crawlerWithNodes = $crawler->filterXPath('/_root/foo/foo');

$this->assertEquals('bar', $crawlerWithNodes->text());
}

希望这有帮助

关于symfony - XPath:使用相对路径获取值(PHP、Symfony、DOMCrawler)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32152015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com