javascript - php 抓取的页面如何处理可以只保留DOM结构,去掉CSS和JS?
迷茫
迷茫 2017-04-10 12:44:33
[JavaScript讨论组]

正则规则写好后,页面一旦有改变就要重新修改正则。
先提取页面的 DOM,有没有比较好的办法?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(2)
天蓬老师

我想你需要的是 php 的 DOM 模块 ... 默认有安装不用担心 ...

因为不知道你的实际应用场景是什么 ... 给你写个简单的例子吧 ...

<?php
/* i heard that you need DOM ..? */
$doc = new DOMDocument();

/* i wrote a simple page ... change it to a curl result ... */
$doc->loadHTML( <<<HTML_SECTION
<html><head><title>Sunyanzi's Test</title></head>
<body>
  <h1>Hello World</h1>
  <a href="http://segmentfault.com/" id="onlylink">Hey Welcome</a>
</body></html>
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。。。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号