i am trying to get all external links in one web page and store it in database. i put all web page contents in variable:
$pageContent = file_get_contents("http://sample-site.org");
how i can save all external links??
for example if web page has a code such as:
<a href="http://othersite.com">other site</a>
i want to save http://othersite.com。 换句话说,我想制作一个存储所有外部链接的爬虫存在于一个网页中。 我怎么能这样做?
答案 0 :(得分:4)
您可以使用PHP Simple HTML DOM Parser的find
方法:
require_once("simple_html_dom.php");
$pageContent = file_get_html("http://sample-site.org");
foreach ($pageContent->find("a") as $anchor)
echo $anchor->href . "<br>";
答案 1 :(得分:0)
我建议使用DOMDocument()和DOMXPath()。这样,结果只会包含您要求的外部链接。
作为一个说明。如果您要抓取网站,则更有可能想要使用cURL,但我会继续file_get_contents(),因为您在此示例中使用的是{{3}} 。 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
*/