如何使用PHP抓取网站

Pau*_*des 0 php web-scraping

我使用以下代码获取网站的内容

function get_content($url){
    $content = @file_get_contents($url);
    if( empty($content) ){
      $content = get_url_contents($url);
    }
    return $content;
}

function get_url_contents($url){
    $crl = curl_init();
    $timeout = 90;
    curl_setopt ($crl, CURLOPT_URL,$url);
    curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
    $ret = curl_exec($crl);
    curl_close($crl);
    return $ret;
}

$url = "http://www.site.com";
$html = get_content($url);
echo $html;
Run Code Online (Sandbox Code Playgroud)

一切都很好,但我需要得到所有我的div元素或页面标题或我的所有图像.

我怎样才能做到这一点?

谢谢

xbo*_*nez 5

使用HTML Parsing库.虽然其中很多都存在,但我个人使用SimpleHTMLDom并且拥有良好的体验.它使用JQuery样式选择器,使其易于学习.

一些代码示例:

要获得页面标题:

$html = str_get_html($html);
$title = $html->find('title',0);
echo $title->plaintext;
Run Code Online (Sandbox Code Playgroud)

对于所有div元素:

$html = str_get_html($html);
$divs = $html->find('div');

foreach($divs as $div) {
   // do something;
}
Run Code Online (Sandbox Code Playgroud)