作者:小白石 | 来源:互联网 | 2017-05-14 02:20
正则规则写好后,页面一旦有改变就要重新修改正则。
先提取页面的 DOM,有没有比较好的办法?
回复内容:
正则规则写好后,页面一旦有改变就要重新修改正则。
先提取页面的 DOM,有没有比较好的办法?
我想你需要的是 php 的 DOM 模块 ... 默认有安装不用担心 ...
因为不知道你的实际应用场景是什么 ... 给你写个简单的例子吧 ...
loadHTML( <<
Hello World
Hey Welcome
HTML_SECTION
);
/* now we should try to get something ... */
$h1Elements = $doc->getElementsByTagName( 'h1' );
/* this line prints "Hello World" ... */
foreach( $h1Elements as $h1Node )
echo $h1Node->nodeValue, PHP_EOL;
/* and this line prints "http://segmentfault.com/" ... */
echo $doc->getElementById( 'onlylink' )->getAttribute( 'href' ), PHP_EOL;
/* now i will introduce something advanced ... using XPath ... */
$xpath = new DOMXPath( $doc );
/* also prints "http://segmentfault.com/" ... locate via h1 ... */
echo $xpath->evaluate(
'string(//h1[text()="Hello World"]/following-sibling::a/@href)'
), PHP_EOL;
基本上 ... 等到你熟练掌握 XPath 之后 ... 你会发现 DOM 比正则要灵活得多 ...
php 处理 XML 的能力远远超乎你的想象 ... 有空读读手册不是坏事恩 ...
你说的很对。我现在就用xpath。。。