本教程演示瞭如何使用開源解析器有效地解析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中文網其他相關文章!