到目前为止,我正在构建一个与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;
但是,这会刮掉整个页面,就像媒体导入工具对任何链接所做的那样,仅找到和刮擦主要内容是可能的
请解决这个问题,我怎样才能获得这种结果
答案 0 :(得分:1)
我不确定您要问/想做什么。.但是我会尝试一下。
您正试图确定主要内容区域-仅刮取所需的信息,而没有任何垃圾或不需要的内容。
我的方法是使用格式良好的HTML页面的通用结构和良好做法。考虑一下:
ARTICLE
标签中。H1
标签将是其标题。在目标上总结这些规则,并建立一个按优先级排序的标识符列表->然后,您可以尝试解析目标,直到找到一个标识符为止-这表明您已标识了主要内容区域。
以下是示例->使用您提供的网址:
$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…
希望我能帮上忙。