本教程演示了如何使用开源解析器有效地解析HTML,从而避免了正则表达式的复杂性。 我们将以一个例子为例,提取文章标题和描述。 这是出于说明目的;请记住在刮去网站之前始终获得许可。
首先安装PHP软件包管理器Composer,以简化库安装。
>
文档
核心代码段:
这包括必要的库,并初始化一个数组来存储文章数据。
use voku\helper\HtmlDomParser; require_once 'vendor/autoload.php'; $articles = []; getArticles('https://code.tutsplus.com/tutorials');
>
getArticles
>通过每个文章元素(
$items = $html->find('article'); foreach($items as $post) { $articles[] = [ /* title */ $post->findOne(".posts__post-title")->firstChild()->text(), /* description */ $post->findOne("posts__post-teaser")->text() ]; }
<article>
$articles
$articles[0][0] = "My Article Name Here"; $articles[0][1] = "This is my article description";
相关的html:
以获取后续页面。 至关重要的是,要清除
的对象以防止记忆力耗尽。<a aria-label="next" class="pagination__button pagination__next-button" href="https://www.php.cn/link/a3cdf7cabc49ea4612b126ae2a30ecbf" rel="next"><i class="fa fa-angle-right"></i></a>
解析大型网站可能很耗时。 本教程为使用用户友好的库提供了HTML解析的基础。 尽管此库很方便,但请记住,存在其他方法,例如PHP的内置DOM操纵与XPath的操作。 在刮擦任何网站之前,请始终优先获取许可。
以上是使用简单的HTML DOM库进行HTML解析和屏幕刮擦的详细内容。更多信息请关注PHP中文网其他相关文章!