【问题标题】:using simple html dom to scrape使用简单的 html dom 来抓取
【发布时间】:2014-09-26 11:33:53
【问题描述】:

我正在尝试使用 simple_html_dom 抓取一些内容,但没有运气。

我正在尝试获取标题、图像路径和链接并显示它。

HTML 结构是:

<div class="article_item clearfix">
<h2 class="title"><a href="http://www.demodomain/articleid=1">My amazing Title</a></h2>
<p class="date">September 22 2014</p>
<p class="image_left">
<a href="http://www.demodomain/articleid=1">
<img src="http://www.demodomain/photos/cef78533cd5.jpg" alt="My amazing post ">
</a>
</p>
<p>This is a demo description<strong>of this amazing</strong> article</p>
<p class="more"><a href="http://www.demodomain/articleid=1" class="blued_links">Read more...</a></p>
</div>

到目前为止我的代码:

foreach($html->find('article_item') as $article) {
    $item['title']   = $article->find('.title, a', 0)->plaintext;
    $item['thumb']  = $article->find('.image_left img', 0)->src;
    $item['details'] = $article->find('p', 0)->plaintext;
    $item['url'] = $article->find('.more, a', 0)->plaintext;
       


echo 'Title: ' . $item['title'];
echo "</br>";
echo "image url: " . $item['thumb'];
echo "</br>";
echo "Description: " . $item['details'];
echo "</br>";
echo "Read More Url: " . $item['url'];
}



// Clear dom object
$html->clear(); 
unset($html); 

【问题讨论】:

  • 那么什么不起作用?你遇到了什么错误?
  • 这甚至都不是问题。

标签: php html simple-html-dom


【解决方案1】:

您没有说明什么不起作用,但请考虑以下示例:

foreach($html->find('div.article_item') as $div) {
                 //  ^ point to div tag with class name article_item
    $title = $div->find('h2.title a ', 0)->innertext;
                     // ^ target the h2 tag with class title with child anchor
                     // just same as accessing dom with jquery
    $thumb = $div->find('p.image_left img ', 0)->src;
    $details = $div->children(3)->plaintext;
    // $url = $div->find('p.more', 0)->plaintext;
    $url = $div->find('p.more a', 0)->href;

    echo $title . '<br/>';
    echo $thumb . '<br/>';
    echo $details . '<br/>';
    echo $url . '<br/>';
}

基本上,这与选择选择器相同。

【讨论】:

  • 伟大的幽灵先生......非常感谢!从 $url 我需要获取一个 href 链接。请问这怎么可能?
  • @IreneT。做了修改,再试一次
  • @IreneT。肯定不会很高兴这有帮助
【解决方案2】:

你可以这样试试

$item['title']   = $article->find('h2.title')->plaintext;
$item['thumb']  = $article->find('p.image_left')->find('img')->src;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-04
    • 2013-07-30
    • 1970-01-01
    • 2021-05-18
    • 2013-12-26
    • 2015-01-07
    • 2016-02-22
    • 1970-01-01
    相关资源
    最近更新 更多