尝试使用php和DOM抓取链接


Trying to scrape links using php and DOM

如果我有以下的X(HTML)结构,如何在div树的深处捕获imgur链接?

我尝试了几种不同的方法。我真正想要的是为包含"siteTable"的div做一个节点树,因为在那个div中有许多div包含更多的imgur链接。如果你没有注意到,这是reddit的html。

谢谢!

<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<body class="listing-page hot-page">
    <div id="header" role="banner">
    <div class="side">
    <a name="content"></a>
    <div class="content" role="main">
    <div class="infobar welcome">
    <div id="siteTable" class="sitetable linklisting">
        <div class=" thing id-t3_1gh823 over18 odd link " data-downs="5" data-ups="90" data-fullname="t3_1gh823" onclick="click_thing(this)">
            <p class="parent"></p>
            <span class="rank" style="width:2.20ex;">1</span>
            <div class="midcol unvoted" style="width:5ex;">
            <a class="thumbnail " href="http://i.imgur.com/FZ1I9wi.jpg">

这是我知道需要做的:

    $dom = new domDocument;

    @$dom->loadHTML(file_get_contents($link));

    $dom->preserveWhiteSpace = false;

    $xpath = new DOMXPath($dom);
    $href = $xpath->query('?????');
    print_r($tags);

我总是尽量使XPath更基本,但更具体。这使得在页面更改时更容易更改和调试。如果不查看整个页面或多个reddit页面,很难说……但我假设thumbnail类仅用于您想要的缩略图链接。在本例中,我们可以创建一个非常简单(但具体)的XPath查询:

$link_nodes = $xpath->query('//a[@class="thumbnail"]');
if($link_nodes->length > 0) {
  // you can do a foreach loop here if there may be multiple links?
  $link_node = $link_nodes->item(0);
  $href = $link_node->attributes->getNamedItem('href')->value;
}

另外,您可能希望通过增强XPath查询来确保获得imgur链接:

$link_nodes = $xpath->query('//a[@class="thumbnail"][contains(@href, "imgur.com")]');

可以借助HTML DOM解析器。下载并将其包含在脚本中。然后使用下面的代码解析url。

如何包含脚本:

if (!function_exists('file_get_html')) {
require_once( 'public/frontend/simple_html_dom.php');
}

解析:

$scrape_url = 'http://www.example.com/a.php';
$html = file_get_html($scrape_url);
echo $html->find('div[siteTable]');