试图从网页上抓取所有facebook链接


trying to scrape all facebook links from a web page

我正试图从Facebook上抓取页面链接。但是,我得到一个空白页,没有任何错误消息。

我的代码如下:
<?php
error_reporting(E_ALL);
function getFacebook($html) {
    $matches = array();
    if (preg_match('~^https?://(?:www'.)?facebook.com/(.+)/?$~', $html, $matches)) {
        print_r($matches);
    }
}
$html = file_get_contents('http://curvywriter.info/contact-me/');
getFacebook($html);

怎么了?

一个更好的选择(也是更健壮的)是使用DOMDocument和DOMXPath:

<?php
error_reporting(E_ALL);
function getFacebook($html) {
    $dom = new DOMDocument;
    @$dom->loadHTML($html);
    $query = new DOMXPath($dom);
    $result = $query->evaluate("(//a|//A)[contains(@href, 'facebook.com')]");
    $return = array();
    foreach ($result as $element) {
        /** @var $element DOMElement */
        $return[] = $element->getAttribute('href');
    }
    return $return;
}
$html = file_get_contents('http://curvywriter.info/contact-me/');
var_dump(getFacebook($html));

对于你的具体问题,我做了以下的事情:

  • preg_match更改为preg_match_all,以便在第一次发现后不停止。
  • 从模式中删除^(开始)和$(结束)字符。你的链接将出现在文档的中间,而不是开始或结束(绝对不是两者都出现!)

所以更正后的代码是:

<?php
error_reporting(E_ALL);
function getFacebook($html) {
    $matches = array();
    if (preg_match_all('~https?://(?:www'.)?facebook.com/(.+)/?~', $html, $matches)) {
        print_r($matches);
    }
}
$html = file_get_contents('http://curvywriter.info/contact-me/');
getFacebook($html);