如何从.html页面中提取链接和标题?

Ton*_*bet 28 html php string web-crawler hyperlink

对于我的网站,我想添加一个新功能.

我希望用户能够上传他的书签备份文件(如果可能的话,从任何浏览器上传),这样我就可以将其上传到他们的个人资料中,而且他们不必手动插入所有这些文件...

这是我唯一缺少这样做的部分,它是从上传的文件中提取标题和URL的部分..任何人都可以提供线索从何处开始或在哪里阅读?

使用搜索选项和(如何从原始html文件中提取数据)这是我最相关的问题,它没有谈论它..

我真的不介意它是否使用jquery或php

非常感谢你

Ton*_*bet 61

谢谢大家,我知道了!

最终代码:这将显示分配的文本和.html文件中所有链接的href

$html = file_get_contents('bookmarks.html');
//Create a new DOM document
$dom = new DOMDocument;

//Parse the HTML. The @ is used to suppress any parsing errors
//that will be thrown if the $html string isn't valid XHTML.
@$dom->loadHTML($html);

//Get all links. You could also use any other tag name here,
//like 'img' or 'table', to extract other tags.
$links = $dom->getElementsByTagName('a');

//Iterate over the extracted links and display their URLs
foreach ($links as $link){
    //Extract and show the "href" attribute.
    echo $link->nodeValue;
    echo $link->getAttribute('href'), '<br>';
}
Run Code Online (Sandbox Code Playgroud)

再次,非常感谢.

  • @benjaminhull 是为了防止代码抛出任何警告;) (2认同)

Mat*_*hew 36

这可能就足够了:

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node)
{
  echo $node->nodeValue.': '.$node->getAttribute("href")."\n";
}
Run Code Online (Sandbox Code Playgroud)

  • whre $ html它是文件的路径?谢谢你这么快的回答:D (2认同)
  • @Toni,`$ html`是包含HTML的字符串.您可以使用`$ dom-> loadHTMLFile()`直接从文件加载.(您可能希望在它前面添加`@`来抑制警告.) (2认同)

Adr*_*uer 6

这是一个例子,你可以在你的情况下使用:

$content = file_get_contents('bookmarks.html');
Run Code Online (Sandbox Code Playgroud)

运行这个:

<?php

$content = '<html>

<title>Random Website I am Crawling</title>

<body>

Click <a href="http://clicklink.com">here</a> for foobar

Another site is http://foobar.com

</body>

</html>';

$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
$regex .= "([a-z0-9-.]*)\.([a-z]{2,4})"; // Host or IP
$regex .= "(\:[0-9]{2,5})?"; // Port
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor


$matches = array(); //create array
$pattern = "/$regex/";

preg_match_all($pattern, $content, $matches); 

print_r(array_values(array_unique($matches[0])));
echo "<br><br>";
echo implode("<br>", array_values(array_unique($matches[0])));
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [0] => http://clicklink.com
    [1] => http://foobar.com
)
Run Code Online (Sandbox Code Playgroud)

http://clicklink.com

http://foobar.com


Sim*_*olt 5

假设存储的链接在html文件中,最好的解决方案可能是使用html解析器,例如PHP Simple HTML DOM Parser(我自己从未尝试过).(另一种选择是使用基本字符串搜索或正则表达式进行搜索,您可能永远不应该使用regexp来解析html).

使用解析器读取html文件后,使用它的函数来查找a标记:

从教程:

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>'; 
Run Code Online (Sandbox Code Playgroud)