大学-公司数据爬取

今天需要搞大学数据库,目标是新浪高考网。
仔细分析其页面的数据获取是使用Jsonp的js方式。于是在控制台能使用js爬取了大学数据源(1378条)

这里要记录的是爬取中数组合并的问题

开始的时候,参考 ourjs的文章^3,cnblog上翻译的一篇文章^4 (原作^5)之后,打算尝试reduce

//g,b为数组
g = b.reduce(function (coll, item) {
    coll.push(item);
    return coll;
}, g);

但是发现数据量大了之后,这个所谓的高效反而奇慢,后经同事帮助,我发现了问题
返回的数据格式为:Object { 1=[8], 2=[8], 3=[8], 更多…}
看到没是,json对象或者说是Map,不是数组,而reduce数组内每个元素依次调用回调的方法。


与此同时,我纳闷了为何 concat 就可以,去看了文档

concat creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array).

concat does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains copies of the same elements combined from the original arrays. Elements of the original arrays are copied into the new array as follows:

Object references (and not the actual object): concat copies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays.

Strings and numbers (not String and Number objects): concat copies the values of strings and numbers into the new array[^footer2].
引自:developer.mozilla.org^6

大致意思就是,合并中,如果是数组或者对象就直接复制(原数组对象和拷贝后的合并对象仍指向同一对象),如果是字符串或者数字就把值拷贝。

还是概念没搞清啊。以后要注意了
配图尝试,只为装逼。

这里记录一个二维数组去重的思路:

function array_unique_deep($array2D) {
    foreach ($array2D as $v) {
        //$v['desc'] = mb_stristr($v['desc'], '企业招聘', true);
        $v         = join(",", $v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        $temp[]    = $v;

    }
    $temp = array_unique($temp);    //去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k => $v) {
        $temp[$k] = explode(",", $v);   //再将拆开的数组重新组装
    }

    return $temp;
}

还有excel导入处理:

/**
 * csv_get_lines 读取CSV文件中的某几行数据
 * @param $csvfile csv文件路径
 * @param $lines 读取行数
 * @param $offset 起始行数
 * @return array
 * */
function csv_get_lines($csvfile, $lines, $offset = 0) {
    if(!$fp = fopen($csvfile, 'r')) {
        return false;
    }
    $i = $j = 0;
    while (false !== ($line = fgets($fp))) {//从文件指针中读取一行
        if($i++ < $offset) {
            continue;
        }
        break;
    }
    $data = array();
    while(($j++ < $lines) && !feof($fp)) {
        $_tmp=fgetcsv($fp);//从文件指针中读入一行并解析 CSV 字段
        if(!empty($_tmp[0])){
            $data[] = $_tmp;
        }
    }
    fclose($fp);
    return $data;
}
如有疑问,请文末留言交流或邮件:newbvirgil@gmail.com 本文链接 : https://newbmiao.github.io/2015/07/31/school-company-data-crawling.html