bdk / css-xpath
通过CSS选择器搜索HTML或将CSS选择器转换为XPath
v1.0.1
2023-09-19 03:39 UTC
Requires
- php: >=5.3.0
Requires (Dev)
- phpunit/phpunit: ^4.0 | ^5.0 | ^6.0 | ^7.0 | ^8.0 | ^9.0
This package is auto-updated.
Last update: 2024-09-19 05:49:16 UTC
README
- 将CSS选择器转换为XPath
- 通过CSS选择器查询HTML字符串(或\DOMDocument)
- 提供PHPUnit断言(由PHPUnit提供)
安装
composer require bdk/css-xpath
使用方法
CSS到XPath
\bdk\CssXpath\CssXpath::cssToXpath('ul > li:first-child'); // returns '//ul/li[1]'
查询DOM/HTML
示例
$html = <<<HTML <div id="article" class="block large"> <h2>Article Name</h2> <p>Contents of article</p> <ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li><a href="#">Five</a></li> </ul> </div> HTML; // use static method var_dump(\bdk\CssXpath\CssSelect::select($html, 'ul > li:last-child [href]')); // or create and use an instance $cssSelect = new \bdk\CssXpath\CssSelect($html); $found = $cssSelect->select('ul > li:last-child [href]');
输出
array (size=1)
0 =>
array (size=3)
'name' => string 'a' (length=1)
'attributes' =>
array (size=1)
'href' => string '#' (length=1)
'innerHTML' => string 'Five' (length=4)
传递最后一个参数为true
,将返回一个\DOMNodeList
对象而不是数组
PHPUnit
bdk\CssXpath\DOMTestCase
继承自\PHPUnit\Framework\TestCase
并提供3个断言
assertSelectCount($selector, $count, $actual, $message = '')
assertSelectRegExp($selector, $pattern, $count, $actual, $message = '')
assertSelectEquals($selector, $content, $count, $actual, $message = '')
这些断言最初是在PHPUnit 3.3中提供的,但在PHPUnit 5.0中被移除