【问题标题】:How to get links of text from an html page? [duplicate]如何从 html 页面获取文本链接? [复制]
【发布时间】:2014-01-07 22:36:38
【问题描述】:

我想从这个网页中获取“http://www.w3schools.com/default.asp”和“http://www.google.com”的链接。我想要<div class="link">里面的<a>标签的链接,这个页面还有很多其他的<a>标签和我不想要他们。如何仅检索特定链接?谁能帮帮我?

<div class="link">
<a href="http://www.w3schools.com/default.asp">
<h4>W3 Schools</h4>
</a>
</div>
<div class="link">
<a href="http://www.google.com">
<h4>Google</h4>
</a>
</div>

【问题讨论】:

标签: php html file-get-contents


【解决方案1】:

使用诸如DOMDocument 之类的DOM Parser 来实现:

$dom = new DOMDocument;
$dom->loadHTML($html); // $html is a string containing the HTML

foreach ($dom->getElementsByTagName('a') as $link) {
    echo $link->getAttribute('href').'<br/>';
}

输出:

http://www.w3schools.com/default.asp
http://www.google.com

Demo.


更新:如果您只想要特定 &lt;div&gt; 内的链接,您可以使用 XPath 表达式查找 div 内的链接,然后遍历它们以获取 @ 987654329@属性:

$dom = new DOMDocument;
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$links_inside_div = $xpath->query("//*[contains(@class, 'link')]/a");

foreach ($links_inside_div as $link) {
    echo $link->getAttribute('href').'<br/>';
}

Demo.

【讨论】:

  • @SarathMohan:更新了我的答案
  • Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity, line: 38 in C:\xampp\htdocs\fetch\bkadafetch.php on line 7这是我执行代码时的输出,第7行包含$dom-&gt;loadHTML($html);
  • 虽然这不是一个很好的做法,但您可以使用@$dom-&gt;loadHTML($html); 来抑制警告。一个更好的主意可能是使用libxml_internal_errors()。见this answer
【解决方案2】:

您可以使用 snoopy PHP 类。 Snoopy 是一个模拟 Web 浏览器的 PHP 类。它自动完成检索网页内容和发布表单的任务,http://sourceforge.net/projects/snoopy/

否则尝试使用 Jquery

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
 <script type="text/javascript">
    $( document ).ready(function() {
         $( ".link a" ).each(function( index ) {
             var link = $( this ).attr("href") );
             alert(link );
         });
    });
</script>

您也可以使用此链接获取所有链接(javascript)

 var list = document.getElementsByTagName("a");

【讨论】:

    【解决方案3】:
    $dom = new DOMDocument;
    $dom->loadHTML($html);
    foreach ($dom->getElementsByTagName('a') as $node)
    {
      echo $node->nodeValue.': '.$node->getAttribute("href")."\n";
    }
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签