`

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扩展抓取网页类.zip

    在PHP开发中,有时我们需要从远程网站获取数据...总之,`php应用curl扩展抓取网页类.zip`提供的这个PHP类库,结合cURL扩展,为开发者提供了一种高效、灵活的方式来抓取和处理远程网页数据,是Web开发中的一种实用工具。

    PHP使用Curl实现模拟登录及抓取数据功能示例

    在PHP开发中,有时我们需要获取一些需要用户登录后才能访问的网页内容,此时可以借助Curl库来模拟登录过程并抓取数据。Curl库是一个强大的URL处理工具,支持多种协议,包括HTTP、HTTPS等,它能让我们在PHP中发送HTTP...

    php的curl抓数据专用.zip

    在PHP开发中,cURL库是一个非常重要的工具,它允许开发者通过HTTP、HTTPS和其他协议发送请求,用于数据抓取、网页交互以及API调用等多种用途。"php的curl抓数据专用.zip"这个压缩包文件很可能包含了一个封装好的PHP...

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

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

    PHP curl 抓取AJAX异步内容示例

    总结来说,通过PHP curl抓取AJAX异步内容需要理解和使用HTTP请求相关的各种技术,包括了解如何正确设置请求头、传递参数以及处理响应。通过熟练掌握这些技术,即使是异步加载的内容,也能轻松地从服务器端获取到所需...

    php通过curl添加cookie伪造登陆抓取数据的方法

    在PHP开发中,有时我们需要从特定的网页抓取数据,尤其是那些需要用户登录后才能访问的页面。这种情况下,可以通过模拟登录,即“伪造登录”来实现数据抓取。本篇将详细介绍如何利用PHP的cURL库添加cookie来实现这个...

    php扩展 php_curl

    总结来说,`php_curl`扩展是PHP进行网络通信的重要工具,它提供的功能强大且灵活,使得开发者可以轻松地进行数据抓取、文件上传下载、API调用等各种网络操作。通过熟练掌握`php_curl`,你可以编写出更健壮、高效的...

    curl配合simple_html_dom进行页面数据抓取

    本示例介绍了一种结合`curl`和`simple_html_dom`库的方法,用于高效地从网页中抓取数据。`curl`是用于传输数据的PHP扩展,而`simple_html_dom`是一个方便的PHP类,可以解析HTML并提取所需信息。 首先,`curl`...

    php的curl抓数据专用

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

    php应用curl扩展抓取网页类

    本篇文章将深入探讨如何使用PHP的cURL扩展来抓取网页内容,以及如何创建一个类来封装这个功能。我们将讨论以下几个方面: 1. **cURL介绍** cURL是一个命令行工具,同时也提供了PHP的扩展,使得开发者可以在PHP脚本...

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

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

    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批量请求url

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

    php中curl.exe运行文件

    在PHP开发中,`curl` 是一个非常重要的库,用于...总之,`curl`是PHP中不可或缺的数据抓取工具,无论是在命令行还是通过PHP扩展,都能提供强大的网络请求功能。学习并熟练掌握`curl`,将极大地提升你的Web开发效率。

    php下curl用法详解

    通过以上步骤,我们可以实现诸如登录、页面抓取、API调用等各种网络操作。cURL的强大之处在于它的灵活性和可配置性,可以根据需求定制各种网络请求行为。记住,使用cURL时要确保遵循网站的使用条款和robots.txt文件...

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

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

    PHP100视频教程88:PHP.之.CURL模拟登陆并获取数据.rar

    【PHP与CURL模拟登录及数据获取】 在Web开发中,有时我们需要模拟用户登录到某个网站,以便自动化处理一些任务或获取受保护的数据。在这个PHP100视频教程88中,我们将深入学习如何利用PHP的cURL库来实现这个功能。...

    PHP抓取网页数据代码

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

    【curl】phpQuery应用

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

Global site tag (gtag.js) - Google Analytics