首页 > 解决方案 > 使用 php 抓取主要内容

问题描述

到目前为止,我正在构建一个导入工具,就像 medium.com 故事导入工具一样,我已经使用了这个代码

include('includes/import/simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('https://neilpatel.com/blog/starting-over/');

// find all link
foreach($html->find('a') as $e) 
    echo $e->href . '<br>';

// find all image
foreach($html->find('img') as $e)
    echo $e->src . '<br>';

// find all image with full tag
foreach($html->find('img') as $e)
    echo $e->outertext . '<br>';

// find all div tags with id=gbar
foreach($html->find('div#gbar') as $e)
    echo $e->innertext . '<br>';

// find all span tags with class=gb1
foreach($html->find('span.gb1') as $e)
    echo $e->outertext . '<br>';

// find all td tags with attribite align=center
foreach($html->find('td[align=center]') as $e)
    echo $e->innertext . '<br>';

// extract text from table
echo $html->find('td[align="center"]', 1)->plaintext.'<br><hr>';

// extract text from HTML
echo $html->plaintext;

但是这个刮整个页面是有可能只找到和刮掉主要内容,就像媒体导入工具对任何链接所做的那样

请解决这个问题,我怎样才能达到这种结果

标签: javascriptphpjqueryhtmlregex

解决方案


我不完全确定你在问/试图做什么。但我会试一试。

您正在尝试识别主要内容区域 - 只抓取需要的信息,而没有任何垃圾或不需要的内容。

我的方法是使用格式良好的 HTML 页面的常见结构和良好实践。考虑一下:

  • 主要文章将被封装在ARTICLE页面上的唯一标签中。
  • 文章上的H1标签将是它的标题。
  • 我们知道有一些重复的 ID 被使用,例如 (main_content, main_article, etc..)。

总结目标上的这些规则并构建按优先级排序的标识符列表 -> 然后您可以尝试解析目标,直到找到其中一个标识符 - 这表明您确定了主要内容区域。

这是一个示例 -> 使用您提供的 URL:

$search_logic = [
    "#main_content",
    "#main_article",
    "#main",
    "article",
];

// get DOM from URL or file
$html = file_get_contents('https://neilpatel.com/blog/starting-over/');
$dom = new DOMDocument ();
@$dom->loadHTML($html);

//
foreach ($search_logic as $logic) {

    $main_container = null;

    //Search by ID or By tag name:
    if ($logic[0] === "#") {
        //Serch by ID:
        $main_container = $dom->getElementById(ltrim($logic, '#'));
    } else {
        //Serch by tag name:
        $main_container = $dom->getElementsByTagName($logic);
    }

    //Do we have results:
    if (!empty($main_container)) {

        echo "> Found main part identified by: ".$logic."\n";
        $article = isset($main_container->length) ? $main_container[0] : $main_container; // Normalize the container.

        //Parse the $main_container:
        echo " - Example get the title:\n";
        echo "\t".$article->getElementsByTagName("h1")[0]->textContent."\n\n";

        //You can stop the iteration:
        //break;

    } else {
        echo "> Nothing on the page containing: ".$logic."\n\n";
    }
}

正如您所看到的,没有找到 ID 的第一个,所以我们继续尝试列表,直到我们达到我们想要的结果 -> 一组好的这些标记名/ID 就足够了。

结果如下:

> Nothing on the page containing: #main_content

> Nothing on the page containing: #main_article

> Found main part identified by: #main
 - Example get the title:
    If I Had to Start All Over Again, I Would…

> Found main part identified by: article
 - Example get the title:
    If I Had to Start All Over Again, I Would…

希望我有所帮助。


推荐阅读