首页 >后端开发 >php教程 >使用简单的HTML DOM库进行HTML解析和屏幕刮擦

使用简单的HTML DOM库进行HTML解析和屏幕刮擦

Lisa Kudrow
Lisa Kudrow原创
2025-02-28 10:50:16793浏览

本教程演示了如何使用开源解析器有效地解析HTML,从而避免了正则表达式的复杂性。 我们将以一个例子为例,提取文章标题和描述。 这是出于说明目的;请记住在刮去网站之前始终获得许可。


  1. >设置

首先安装PHP软件包管理器Composer,以简化库安装。

HTML Parsing and Screen Scraping With the Simple HTML DOM Library

其他步骤在下面详细介绍。

>

文档

综合文档可在该项目的官方GitHub存储库中获得。

---

HTML Parsing and Screen Scraping With the Simple HTML DOM Library

    实用应用:刮擦envato tuts
  1. >让我们创建一个脚本来从Envato Tuts中提取文章标题和描述。 这是一个演示,不应在未经许可的情况下进行。 刮擦可以超载服务器。

HTML Parsing and Screen Scraping With the Simple HTML DOM Library 核心代码段:

这包括必要的库,并初始化一个数组来存储文章数据。
<code class="language-php">use voku\helper\HtmlDomParser;
require_once 'vendor/autoload.php';

$articles = [];
getArticles('https://code.tutsplus.com/tutorials');</code>
>函数(稍后定义)获取并处理网页。

> getArticles


    数据提取
  1. 脚本的核心提取文章信息:

>通过每个文章元素(
<code class="language-php">$items = $html->find('article');
foreach($items as $post) {
    $articles[] = [
        /* title */ $post->findOne(".posts__post-title")->firstChild()->text(),
        /* description */ $post->findOne("posts__post-teaser")->text()
    ];
}</code>
)迭代,并使用CSS选择器提取标题和描述。 每个条目将包含一个标题和描述对。 例如:

<article></article> $articles

<code class="language-php">$articles[0][0] = "My Article Name Here";
$articles[0][1] = "This is my article description";</code>

>处理分页
  1. 要处理多个页面,我们确定“下一个”页面链接:>

HTML Parsing and Screen Scraping With the Simple HTML DOM Library 相关的html:HTML Parsing and Screen Scraping With the Simple HTML DOM Library HTML Parsing and Screen Scraping With the Simple HTML DOM Library

脚本找到了此链接,提取属性,然后递归调用

以获取后续页面。 至关重要的是,要清除

的对象以防止记忆力耗尽。
<code class="language-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></code>
>

结论

解析大型网站可能很耗时。 本教程为使用用户友好的库提供了HTML解析的基础。 尽管此库很方便,但请记住,存在其他方法,例如PHP的内置DOM操纵与XPath的操作。 在刮擦任何网站之前,请始终优先获取许可。

以上是使用简单的HTML DOM库进行HTML解析和屏幕刮擦的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn