温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用CURL构建爬虫,抓取百度百科内容

发布时间:2020-08-04 10:36:23 来源:网络 阅读:1141 作者:jokance 栏目:web开发

实现这个功能的步骤:

首先打开百度百科,在搜索框输入“php”关键词,得到搜索列表,一般都是10条;

然后使用火狐的Firebug分析百度列表的内容组成,主要是html标签,发现去向百科内容的连接的格式都是http://baike.baidu.com/view/5721060.htm,于是使用正则匹配链接,得到10条链接;

之后把链接交由curl()批处理函数(自定义)处理,得到结果页面的内容;

然后在对内容页面进行分析,找出你想要的内容,本程序抓取的是标题以及简介;

最后,把结果呈现在tabel标签中。

此外,我还把抓取的数据写入了数据库中。

所有的代码如下:

程序名为curl.php的代码:


<?php
    require 'func.curl.php';
    require 'func.mysql.php';
    //CURL
    if (isset($_GET['action'])){
        $_key=$_POST['key'];
        $_ch=curl_init();
        curl_setopt($_ch,CURLOPT_URL,"http://baike.baidu.com/search?word=".$_key);
        curl_setopt($_ch,CURLOPT_RETURNTRANSFER,1);
        $_output=curl_exec($_ch);
        curl_close($_ch);
        if(preg_match_all('/(http\:\/\/baike\.baidu\.com.*)\"\s/',$_output,$_url)){
            $_res=curl($_url[1]);
            $_title=array();
            $_content=array();
            for ($_i=0;$_i<count($_res);$_i++){
                if (preg_match_all('/lemmaTitleH1\"\>(.*?)\s*\<\/div\>/',$_res[$_i],$_arr)){
                    //标题
                    $_title[$_i]=strip_tags($_arr[1][0]);
                    if (preg_match_all('/para\"\>(.*?)\s*\<\/div\>/',$_res[$_i],$_arr)){
                        //内容
                        $_content[$_i][0]=strip_tags($_arr[1][0]);
                        $_content[$_i][1]=strip_tags($_arr[1][1]);
                        //插入数据库
                        inserInfo($_title[$_i],$_content[$_i][0],$_content[$_i][1],$_key);
                    }
                }
            }
        }else{
            exit('无匹配结果');
        }
    }
?>   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<title>模拟搜索引擎</title>
<link type="text/css" rel="stylesheet" href="curl.css"/>
</head>
<body>
    <div id="header">
        <form method="post" action="?action=search">
            <input type="text" name="key" value="请输入关键字" class="text"/>
            <input type="submit" name="submit" value="搜索" class="submit"/>
        </form>
    </div>
    <div id="content">
        <table>
        <?php for ($i=0;$i<count($_title);$i++){?>
        <tr><td class="title"><a href="<?php echo $_url[1][$i];?>" target="_blank"><?php echo $_title[$i];?></a></td></tr>
        <tr><td class="content"><?php echo $_content[$i][0]?></td></tr>
        <?php }?>
        </table>
    </div>
<script type="text/javascript">
    var key=document.getElementsByName('key')[0];
    key.onfocus=function(){
            this.value='';
        };
    key.onblur=function(){
            if(this.value==""){
                    this.value="请输入关键字";
                }
        };
</script>
</body>
</html>

func.curl.php的代码:

<?php
//curl批处理函数
function curl($connomains){
           
    $mh = curl_multi_init();
           
    foreach ($connomains as $i => $url) {
     $conn[$i] = curl_init("$url");
     curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
     curl_multi_add_handle ($mh,$conn[$i]);
    }
           
    // start performing the request
    do {
     $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
           
    while ($active and $mrc == CURLM_OK) {
     // wait for network
     if (curl_multi_select($mh) != -1) {
     // pull in any new data, or at least handle timeouts
     do {
     $mrc = curl_multi_exec($mh, $active);
     } while ($mrc == CURLM_CALL_MULTI_PERFORM);
     }
    }
    // retrieve data
    foreach ($connomains as $i => $url) {
     if (($err = curl_error($conn[$i])) == '') {
     $res[$i]=curl_multi_getcontent($conn[$i]);
     } else {
     print "Curl error on handle $i: $err\n";
     }
     curl_multi_remove_handle($mh,$conn[$i]);
     curl_close($conn[$i]);
    }
    curl_multi_close($mh);
           
    return $res;
           
}
?>

func.mysql.php的代码为:

<?php
function inserInfo($_title,$_content,$_content_extra,$_keywords){
        $_mysql=mysql_connect('localhost','root','123') or die('数据库连接错误');
        mysql_select_db('baike',$_mysql);
        mysql_query('set names utf8');
          
        mysql_query("INSERT INTO info (title,content,content_extra,keywords)
                VALUES(
                        '$_title',
                        '$_content',
                        '$_content_extra',
                        '$_keywords'
                        )
      
                        ");   
        mysql_close();           
}
?>


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI