zoukankan      html  css  js  c++  java
  • 超简易简易PHP爬虫

    利用CURL和DOMDocument、通过xpath筛选数据,实现的简易PHP爬虫

    <?php
    header('Content-type: text/plain; charset=utf-8');
    
    $target_url = "http://www.baidu.com";
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $target_url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $html = curl_exec($ch);
    
    if (!$html) {
        echo "<br />cURL error number:" .curl_errno($ch);
        echo "<br />cURL error:" . curl_error($ch);
        exit;
    }
    
    //创建一个DomDocument对象,用于处理一个HTML
    $dom = new DOMDocument();
    //从一个字符串加载HTML
    @$dom->loadHTML($html);
    //使该HTML规范化
    $dom->normalize();
    
    //用DOMXpath加载DOM,用于查询
    $xpath = new DOMXPath($dom);
    #获取所有的a标签的地址
    $hrefs = $xpath->evaluate('//*[@id="u1"]/a');
    
    for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $linktext = $href->nodeValue;
        echo $linktext . PHP_EOL;
    }
    
    ?>
    
    <hr>
    <pre>
    <?= $html ?>
    </pre>
  • 相关阅读:
    Cookie工具类
    验证工具类
    压缩工具类
    一次外企QQ面试
    利用Referer请求头阻止"盗链"
    servlet中ServletConfig的使用
    jquery插件制作
    jQuery选择器总结(转)
    js文件加载执行顺序
    mysql有关问题之:the security settings could not be applied to
  • 原文地址:https://www.cnblogs.com/zjfree/p/11763156.html
Copyright © 2011-2022 走看看