簡體   English   中英

<a>使用PHP</a>獲取<a>頁面中的</a>所有<a>標簽href</a>

[英]get all <a> tags href in page with php

我試圖在一個網頁上獲取所有外部鏈接,並將其存儲在數據庫中。 我將所有網頁內容放入變量中:

$pageContent = file_get_contents("http://sample-site.org");

我如何保存所有外部鏈接?

例如,如果網頁具有以下代碼:

<a href="http://othersite.com">other site</a>

我想將http://othersite.com保存在數據庫中。 換句話說,我要使一個存儲所有外部鏈接的搜尋器存在於一個網頁中。 我該怎么做?

您可以使用PHP Simple HTML DOM Parserfind方法:

require_once("simple_html_dom.php");
$pageContent = file_get_html("http://sample-site.org");
foreach ($pageContent->find("a") as $anchor)
    echo $anchor->href . "<br>";

我建議使用DOMDocument()DOMXPath() 這樣可以使結果僅包含您所要求的外部鏈接。

作為說明。 如果您要爬網網站,則您更可能希望使用cURL ,但是我將繼續使用file_get_contents() ,因為在此示例中,這就是您正在使用的內容。 通過cURL,您可以執行設置用戶代理,標題,存儲cookie等操作,並且看起來更像是真實用戶。 一些網站會嘗試阻止機器人。

$html = file_get_contents("http://example.com");

$doc = new DOMDocument();
@$doc -> loadHTML($html);
$xp = new DOMXPath($doc);

// Only pull back A tags with an href attribute starting with "http".
$res = $xp -> query('//a[starts-with(@href, "http")]/@href');

if ($res -> length > 0)
{
    foreach ($res as $node)
    {
        echo "External Link: " . $node -> nodeValue . "\n";
    }
}
else
    echo "There were no external links found.";

/*
 * Output:
 *  External Link: http://www.iana.org/domains/example
 */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM