`

PHP CURL抓取数据简单操作

 
阅读更多

无聊中看到php中curl模块可以抓取数据,简单实现以下:

需求分析:
抓取大众点评数据
住区内容
1,地区
2,分类
3,店铺详细信息,店铺名称,店铺招牌,地址, 电话, 营业时间,人均消费,其他分店(关联其他分店),环境图片
http://m.dianping.com/citylist


1,定义的简单的curl类库:
<?php
namespace getdp;
class CURL {
private $ch;
private $flag_if_have_run;

public function __construct($url) {
      $this->ch = curl_init($url);
      curl_setopt($this->ch, CURLOPT_RETURNTRANSFER , 1 );
}

public function close() {
      curl_close($this->ch);
}

public function __destruct() {
      $this->close();
}

public function set_time_out($timeout) {
      curl_setopt($this->ch, CURLOPT_TIMEOUT, intval($timeout));
      return $this;
}

public function set_referer($referer) {
if (!empty($referer))
     curl_setopt($this->ch, CURLOPT_REFERER , $referer);
     return $this;
}

public function load_cookie($cookie_file) {
     curl_setopt($this->ch, CURLOPT_COOKIEFILE , $cookie_file);
return $this;
}

public function save_cookie($cookie_file="") {
if(empty($cookie_file))
     $cookie_file = tempnam('./', 'cookie');
     curl_setopt($this->ch, CURLOPT_COOKIEJAR , $cookie_file);
     return $this;
}

public function exec () {
     $str = curl_exec($this->ch);
     $this->flag_if_have_run = true;
     return $str;
}

public function post ($post) {
curl_setopt($this->ch, CURLOPT_POST , 1);
curl_setopt($this->ch, CURLOPT_POSTFIELDS , $post );
return $this;
}

public function get_info() {
if($this->flag_if_have_run == true )
return curl_getinfo($this->ch);
else
throw new Exception("aaaaa");
}

public function set_proxy($proxy) {
curl_setopt($this->ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
curl_setopt($this->ch, CURLOPT_PROXY,$proxy);
return $this;
}

public function set_ip($ip) {
if(!empty($ip))
curl_setopt($this->ch, CURLOPT_HTTPHEADER, array("X-FORWARDED-FOR:$ip", "CLIENT-IP:$ip"));
return $ip;
}

public function set_browser($user_agent, $language) {
curl_setopt ($this->ch , CURLOPT_HTTPHEADER, array ("User-Agent: $user_agent","Accept-Language: $language"));
return $this;
}
}


2,使用pdo操作数据库,将解析获取的数据插入数据库
<?php
require 'curl.class.php';
$pdo = new \PDO('mysql:host=localhost;dbname=getdazong', 'root', '');
$pdo->query("set names utf8");

require 'functions.php';

3,functions.php,简单的pdo数据库操作方法
<?php
function getCitys() {
global $pdo;
return $pdo->query("select * from city")->fetchAll();
}

function getCityById($id) {
global $pdo;
return $pdo->query("select * from city where id = $id")->fetch();
}

function getShops(){
global $pdo;
return $pdo->query("select id from shop group by id")->fetchAll();
}

创建的数据库表:
1,city
CREATE TABLE `city` (
   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
   `city` varchar(64) NOT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2506 DEFAULT CHARSET=utf8

2,category
CREATE TABLE `category` (
   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
   `pid` int(11) NOT NULL,
   `name` varchar(255) DEFAULT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=32743 DEFAULT CHARSET=utf8

3,店铺表
CREATE TABLE `shop` (
   `id` int(32) unsigned NOT NULL,
   `name` varchar(255) NOT NULL COMMENT '店铺名称',
   `subname` varchar(255) DEFAULT NULL COMMENT '分店名称',
   `area` varchar(64) NOT NULL COMMENT '店铺区域',
   `address` varchar(255) DEFAULT NULL COMMENT '店铺地址',
   `mobile` varchar(32) DEFAULT NULL COMMENT '联系电话',
   `per_consumption` varchar(12) DEFAULT NULL COMMENT '消费',
   PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
4,店铺环境图片表
CREATE TABLE `shop_image` (
   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
   `shop_id` int(11) NOT NULL,
   `image_path` varchar(255) NOT NULL,
   `type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1:店铺招牌,0,店铺环境图片',
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=526 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC

现在我们开始抓取数据啦:
1:抓取http://m.dianping.com/citylist所有城市数据
<?php
require 'common.php';
$homePage = "http://m.dianping.com/citylist";
$curl = new \getdp\CURL($homePage);
$homePageContent = $curl->exec();
$hrefRegex = "/<a onclick=\"_gaq\.push\(.*\)\" href=\"javascript:window.location.href='\/c([0-9]{1,})\.csf'\" title=\".*\">(.*)<\/a>/i";
preg_match_all($hrefRegex, $homePageContent, $hrefs);

foreach ($hrefs[0] as $k => $v) {
$pdo->query("insert into city values (" . $hrefs[1][$k] .  ", " . "'". $hrefs[2][$k] . "') on duplicate key update id = id");
}

2,获取店铺种类的数据
<?php
set_time_limit(0);
require 'common.php';
$url = "http://m.dianping.com";
$curl = new \getdp\CURL($url);
$curl->save_cookie('./cookie.txt')->load_cookie('./cookie.txt')->set_time_out('30')->exec();

for ($i = 1; $i <= 30000; $i++) {
$url = "http://m.dianping.com/getchildrencategory?categoryid=$i";
$curl = new \getdp\CURL($url);
$content = $curl->save_cookie('./cookie.txt')->load_cookie('./cookie.txt')->exec();
$content = json_decode($content, true);
$message = $content['message'];
if (!empty($message['category']) && is_array($message['category'])) {
foreach ($message['category'] as $category) {
$pdo->query("insert into category values ({$category['categoryId']}, $i, '{$category['categoryName']}') on duplicate key update id = id");
}
}
}

3,获取所有地区的店铺基本信息
<?php
set_time_limit(0);
require 'common.php';

$url = "http://m.dianping.com";
$curl = new \getdp\CURL($url);
$curl->save_cookie('./cookie.txt')->load_cookie('./cookie.txt')->set_time_out('30')->exec();

$cityList = getCitys();
foreach ($cityList as $item){
$index = 1;
while(true){
$url = "http://m.dianping.com/shoplist/{$item['id']}?reqType=ajax&page=$index";
$curl = new \getdp\CURL($url);
$homePageContent = $curl->save_cookie('./cookie.txt')->load_cookie('./cookie.txt')->set_time_out('30')->exec();
$hrefRegex = "/href=\"\/shop\/(.*)\">.*<div class=\"intro Fix\">.*<span>(.*)<\/span>/Us";
preg_match_all($hrefRegex, $homePageContent, $hrefs);
foreach ($hrefs[0] as $k => $v) {
//get shop basic information
$url = "http://m.dianping.com/shop/".$hrefs[1][$k];
$area = $hrefs[2][$k];
$curl = new \getdp\CURL($url);
$homePageContent = $curl->save_cookie('./cookie.txt')->load_cookie('./cookie.txt')->set_time_out('30')->exec();
$regex ="/<div class=\"details-mode shop-info\">.*<img src=\"(.*)\">.*<span class=\"shop-name\">(.*)<\/span>.*<span class=\"price\">.*[人均|消费|费用]:(.*)<\/span>/Us";
preg_match($regex, $homePageContent,$matches);
$sign_image = !empty($matches[1]) ? $matches[1]:'';
$temp_name = !empty($matches[2]) ? $matches[2] :'';
$per_consumption = !empty($matches[3]) ? trim($matches[3]):'';
$regex = "/(.*)\((.*)\)/Us";
preg_match($regex, $temp_name,$temp_matches);
if(count($temp_matches)>0){
$name = $temp_matches[1];
$subname = $temp_matches[2];
}else{
$name = $temp_name;
$subname = '';
}
$regex = "/<i class=\"icon-address\"><\/i>(.*)<i class=\"arrowent\"><\/i>.*href=\"tel:(.*)\"/Us";
preg_match($regex, $homePageContent,$_matches);
$address = !empty($_matches[1])?$_matches[1]:'';
$mobile = !empty($_matches[2])? $_matches[2]:'';
$pdo->query("INSERT INTO shop(id,name,subname,area,address,mobile,per_consumption) VALUES(".$hrefs[1][$k].",'".$name."','".$subname."','".$area."','".$address."','".$mobile."','".$per_consumption."')");
$pdo->query("INSERT INTO shop_image(shop_id,image_path,TYPE) VALUES(".$hrefs[1][$k].",'".$sign_image."',1)");
}
if(count($hrefs[0])<25) break;
$index++;
}
}


4,获取所有店铺的环境图片
<?php
set_time_limit(0);
require 'common.php';

$url = "http://m.dianping.com";
$curl = new \getdp\CURL($url);
$curl->save_cookie('./cookie.txt')->load_cookie('./cookie.txt')->set_time_out('30')->exec();
$shopList = getShops();
foreach ($shopList as $item){
$existedCityids = file_get_contents('./a.txt');
if(is_numeric(strpos($existedCityids,$item['id']))) continue;
$index = 1;
while (true) {
$url = "http://m.dianping.com/shop/{$item['id']}/photos?reqType=ajax&page=$index";
$curl = new \getdp\CURL($url);
$homePageContent = $curl->save_cookie('./cookie.txt')->load_cookie('./cookie.txt')->set_time_out('30')->exec();
    $regex= "/<img src=\"(.*)\" onerror=\"DP\.prior\.nofind\(\)\">/";
    preg_match_all($regex, $homePageContent, $matches);
    foreach ($matches[0] as $k => $v){
    $pdo->query("INSERT INTO shop_image(shop_id,image_path,TYPE) VALUES(".$item['id'].",'".$matches[1][$k]."',0)");
    }
if(count($matches[0])<15) break;
$index++;
}
file_put_contents('./a.txt', $item['id']."\n",FILE_APPEND);
}

 

分享到:
评论

相关推荐

    php curl抓取网页的介绍和推广及使用CURL抓取淘宝页面集成方法

    不过需要注意的是,淘宝的防爬虫策略是不断更新的,因此使用curl抓取淘宝页面的时候,需要考虑到反反爬虫技术的实现,比如设置合适的请求头、使用代理、处理Cookies等。 libcurl是一个客户端的URL传输库,被PHP ...

    php的curl抓数据专用

    当我们需要从其他网站抓取数据时,PHP的cURL库就显得非常实用。cURL库提供了一种在PHP中执行HTTP请求的方法,包括GET、POST、PUT等多种HTTP方法,使得我们可以方便地获取远程资源。 标题“php的curl抓数据专用”...

    PHP 利用Curl实现多线程抓取网页和下载文件

    以下是一个简单的多线程cURL抓取示例: ```php class CurlThread extends \Thread { private $url; public function __construct($url) { $this-&gt;url = $url; } public function run() { $ch = curl_init...

    PHP中使用cURL操作网络资源1

    在本文中,我们将深入探讨如何在PHP 7环境中利用cURL操作网络资源,包括网页抓取、调用WebService接口以及访问HTTPS资源。 一、开发环境 为了进行PHP与cURL的实践,我们需要搭建一个基础的开发环境。在这个案例中,...

    PHP抓取网页数据插入数据库

    总结起来,"PHP抓取网页数据插入数据库"是一个涵盖HTTP请求、HTML解析、数据处理、数据库操作等多个环节的过程。在实际应用中,如监控银行网站上的实时汇率,这一技术可以帮助我们自动化地收集并存储信息,为业务...

    PHP抓取网页数据代码

    总的来说,PHP抓取网页数据涉及的关键技术有HTTP请求、HTML解析、DOM操作以及数据库交互。这个压缩包提供了一个现成的解决方案,可以直接运行并理解数据抓取的整个过程。对于学习和实践PHP数据抓取的开发者来说,这...

    php curl安装 php中没有编译curl的解决方法for windows

    在PHP开发过程中,cURL库是一个非常重要的工具,它允许我们执行HTTP请求并与其他网络服务进行交互。...一旦安装成功,你就可以利用PHP的cURL功能轻松地执行HTTP请求,实现诸如文件上传、下载、网页抓取等多种功能。

    php curl批量请求url

    首先,批量请求URL通常是为了提高效率,例如在数据抓取、接口测试或自动化任务中。批量请求的关键在于创建一个循环,依次对每个URL执行cURL操作。以下是一个简单的`batch.php`示例,展示了如何使用cURL批量请求URL:...

    【curl】phpQuery应用

    在Web开发中,数据抓取和网页解析是常见的需求,而`curl`和`phpQuery`这两个工具就是处理这类任务的强大助手。本文将深入探讨它们的功能、用法以及如何结合使用。 `curl`是命令行工具,用于传输数据到或从服务器,...

    php使用curl简单抓取远程url的方法

    在PHP中,通过内置cURL库,可以轻松地发送请求和处理来自远程服务器的数据,这就是本文所要介绍的“php使用curl简单抓取远程url的方法”。 cURL在PHP中的使用,首先需要了解其主要函数和设置选项。在本例中,`curl_...

    PHP CURL详解

    PHP的CURL库是一种强大的工具,用于在服务器端执行HTTP请求,它支持多种协议,包括HTTP、HTTPS、FTP、FTPS等,是网页抓取、模拟POST和GET请求的重要手段。CURL使得PHP开发者可以方便地与远程服务器进行交互,获取或...

    PHP 实例--CURL实现简单采集-内含源码以及设计说明书(可以自己运行复现).zip

    通过实际操作和调试,你可以加深对CURL和PHP数据抓取的理解,提升编程技能。 总之,这个"PHP 实例--CURL实现简单采集"的课程作业教程旨在帮助学习者掌握使用PHP和CURL进行网页数据采集的技术,是提升Web开发能力的...

    使用PHP curl模拟浏览器抓取网站信息

    以下是一个简单的PHP cURL POST请求的例子: ```php $url = "http://www.mytest.com/curl/login.php"; // 请求的URL地址 $user = "zkg111"; // 用户名 $pass = "123456"; // 密码 $postdata = "user_name={$user}&...

    curl手册 用curl的

    PHP cURL 是一个强大的库,用于在 PHP 中发送网络请求,包括抓取网页内容、模拟HTTP操作等。它使得开发者能够以编程方式获取和交互远程资源,无论这些资源是静态HTML、XML文件,还是动态API接口。本文将详细介绍如何...

    php页面抓取源码(一个小文件)

    8. **数据存储**:抓取的数据通常需要保存起来,这可能涉及到数据库操作(如MySQL、MongoDB)或文件系统(如CSV、JSON)。PHP提供了丰富的接口与这些存储系统交互。 9. **道德与法律问题**:页面抓取应遵守网站的...

    php_curl win8 安装

    本文将详细介绍如何在Windows 8操作系统上安装PHP的cURL扩展,以便你可以利用这个功能丰富的库进行网页抓取、文件上传、HTTP认证等各种网络操作。 首先,让我们了解PHP和cURL。PHP(Hypertext Preprocessor)是一种...

    基于PHP的云集科技笑话抓取WAP简单版php版源码.zip

    该压缩包文件“基于PHP的云集科技笑话抓取WAP简单版php版源码.zip”包含了一个使用PHP语言编写的程序,主要用于从云集科技的WAP(无线应用协议)网站上抓取笑话内容。这个程序可能是一个简单的Web爬虫,用于自动化地...

    CUrlHttp封装curl类

    CUrlHttp封装curl类是一个基于curl库的PHP类,它为开发者提供了更加便捷的方式来执行HTTP请求,如GET、POST以及表单提交等操作。curl库是一个强大的URL传输库,广泛应用于各种网络请求任务,包括文件上传下载、网页...

Global site tag (gtag.js) - Google Analytics