正在分析html页面中的标题和链接


Parsing title and link from html page

我想从这个html页面获得标题和链接:

<div class="gs_r">
    <h3 class="gs_rt">
        <span class="gs_ctc">[BOOK]</span>
        <a href="http://example.com" onmousedown="return scife_clk(this.href,'','res','1')">titleA</a>
    </h3>
    <div class="gs_ggs gs_fl">
        <a href="http://exampleA.pdf" onmousedown="return scife_clk(this.href,'gga','gga','1')">

我怎样才能拿到它们?

这是代码:

<?php
include 'simple_html_dom.php';
$url = 'http://example.com';
$html = file_get_html($url);
//get the first link
foreach($html->find('span[class=gs_ctc]')as $Link){
echo $link;
}
foreach($html->find('div[class=gs_ggs gs_fl]')as $docLink){
echo $docLink;
}
?>

对于第一个链接,它是<span>的兄弟。试试这个:

//get the first link
foreach($html->find('span[class=gs_ctc]') as $link){
    $link = $link->next_sibling();
    echo $link->plaintext;
    echo $link->href;
}

至于第二个链接,它是<div>:的子链接

foreach($html->find('div[class=gs_ggs gs_fl]') as $docLink){
    $link = $docLink->first_child();
    echo $link->href;
}

编辑:第二个链接与第一个链接分组,所以你可以试试这个:

foreach($html->find('span[class=gs_ctc]') as $link){
    foreach($link->parent()->parent()->find('div[class=gs_ggs gs_fl]') as $docLink){
        $link1 = $link->next_sibling();
        $link2 = $docLink->first_child();
        if(preg_match('/'.pdf$/i', $link2->href) === 1){
            echo $link1->plaintext;
            echo $link1->href;
            echo $link2->href;
        }
    }
}