【问题标题】:Selecting a specific div from a extern webpage using CURL使用 CURL 从外部网页中选择特定的 div
【发布时间】:2011-02-03 07:19:12
【问题描述】:

您好,谁能帮我从网页内容中选择特定的 div。

假设我想从网页http://www.test.com/page3.php 获取带有id="wrapper_content" 的div。

我当前的代码看起来像这样:(不工作)

//REG EXP.
$s_searchFor = '@^/.dont know what to put here..@ui';    

//CURL
$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, 'http://www.test.com/page3.php');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
if(!preg_match($s_searchFor, $ch))
{
  $file_contents = curl_exec($ch);
}
curl_close($ch);

// display file
echo $file_contents;

所以我想知道如何使用 reg 表达式来查找特定的 div,以及如何取消设置网页的其余部分,以便 $file_content 只包含 div。

【问题讨论】:

    标签: php regex html curl


    【解决方案1】:
    include('simple_html_dom.php');
    $html = str_get_html($file_contents);
    $elem = $html->find('div[id=wrapper_content]', 0);
    

    下载simple_html_dom.php

    【讨论】:

      【解决方案2】:

      HTML isn't regular,所以你不应该使用正则表达式。相反,我会推荐一个 HTML 解析器,例如 Simple HTML DOMDOM

      如果您打算使用简单的 HTML DOM,您可以执行以下操作:

      $html = str_get_html($file_contents);
      $elem = $html->find('div[id=wrapper_content]', 0);
      

      即使您使用了正则表达式,您的代码仍然无法正常工作。您需要先获取页面的内容,然后才能使用正则表达式。

      //wrong
      if(!preg_match($s_searchFor, $ch)){
          $file_contents = curl_exec($ch);
      }
      
      //right
      $file_contents = curl_exec($ch); //get the page contents
      preg_match($s_searchFor, $file_contents, $matches); //match the element
      $file_contents = $matches[0]; //set the file_contents var to the matched elements
      

      【讨论】:

      • str_get_html() 函数未定义。为什么?
      【解决方案3】:

      检查我们的 hpricot,它可以让您优雅地选择部分

      首先你会使用 curl 获取文档,然后使用 hpricot 获取你需要的部分

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-08
        • 2013-08-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多