Home Backend Development PHP Tutorial php curl抓取网页的介绍和推广及使用CURL抓取淘宝页面集成方法_PHP

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

May 29, 2016 am 11:47 AM

 php的curl可以用来实现抓取网页,分析网页数据用, 简洁易用, 这里介绍其函数等就不详细描述, 放上代码看看:

只保留了其中几个主要的函数。 实现模拟登陆, 其中可能涉及到session捕获, 然后前后页面涉及参数提供形式。

  libcurl主要功能就是用不同的协议连接和沟通不同的服务器~也就是相当封装了的sock

  PHP 支持libcurl(允许你用不同的协议连接和沟通不同的服务器)。, libcurl当前支持http, https, ftp, gopher, telnet, dict, file, 和ldap 协议。libcurl同样支持HTTPS证书授权,HTTP POST, HTTP PUT, FTP 上传(当然你也可以使用PHP的ftp扩展), HTTP基本表单上传,代理,cookies,和用户认证。

  为了使用CURL函数你需要安装CURL包。PHP 需要你使用CURL 7.0.2-beta或更高版。如果CURL的版本低于7.0.2-beta,PHP将不工作。

  要使用PHP的CURL支持,你必须用带有--with-curl[=DIR]参数重新编译PHP(DIR是包含库和头文件的目录)。

  这些函数是在PHP 4.0.2中新增得。

  一旦你编译了带有CURL支持的PHP,你可以使用curl函数。基本思路是:你使用curl_init()函数初始化 CURL会话,而后你可以设置你的所有选项,通过curl_exec()函数执行,最后你可以作用curl_close()函数来结束你的会话。以下是一个例子:是把PHP的主页取回放到一个文件中。

  例 1. 使用PHP的CURL模块取回PHP主页

$ch = curl_init ("http://www.php.net/");
  $fp = fopen ("php_homepage.txt", "w");
  curl_setopt ($ch, CURLOPT_FILE, $fp);
  curl_setopt ($ch, CURLOPT_HEADER, 0);
  curl_exec ($ch);
  curl_close ($ch);
  fclose ($fp);
  ?>
Copy after login

  目录列表

  curl_init — 初始化一个CURL会话

  curl_setopt — 为CURL调用设置一个选项

  curl_exec — 执行一个CURL会话

  curl_close — 关闭一个CURL会话

  curl_version — 返回当前CURL版本

  * curl扩展的安装

  PHP已经内置有php_curl.dll,在ext目录下,此DLL用于支持SSL和zlib.

  在php.ini中找到有extension=php_curl.dll, 去掉前面的注释.

  设置extension_dir=你的php的ext目录(例如c:/php/ext)

  把ext目录下的libeay32.dll, ssleay32.dll, php5ts.dll, php_curl.dll 都拷贝到system32目录下,重启apache即可。

  curl_init

  curl_init -- 初始化一个CURL会话

  描述

int curl_init ([string url])
Copy after login

  curl_init()函数将初始化一个新的会话,返回一个CURL句柄供curl_setopt(), curl_exec(),和 curl_close() 函数使用。如果可选参数被提供,那么CURLOPT_URL选项将被设置成这个参数的值。你可以使用curl_setopt()函数人工设置。

  例 1. 初始化一个新的CURL会话,且取回一个网页

$ch = curl_init();
  curl_setopt ($ch, CURLOPT_URL, "http://www.zend.com/");
  curl_setopt ($ch, CURLOPT_HEADER, 0);
  curl_exec ($ch);
  curl_close ($ch);
  ?>
Copy after login

  参见:curl_close(), curl_setopt()

  * curl_setopt

  curl_setopt -- 为CURL调用设置一个选项

  描述 

 bool curl_setopt (int ch, string option, mixed value)
Copy after login

  curl_setopt()函数将为一个CURL会话设置选项。option参数是你想要的设置,value是这个选项给定的值。

  下列选项的值将被作为长整形使用(在option参数中指定):

  CURLOPT_INFILESIZE: 当你上传一个文件到远程站点,这个选项告诉PHP你上传文件的大小。

  CURLOPT_VERBOSE: 如果你想CURL报告每一件意外的事情,设置这个选项为一个非零值。

  CURLOPT_HEADER: 如果你想把一个头包含在输出中,设置这个选项为一个非零值。

  CURLOPT_NOPROGRESS: 如果你不会PHP为CURL传输显示一个进程条,设置这个选项为一个非零值。

  注意:PHP自动设置这个选项为非零值,你应该仅仅为了调试的目的来改变这个选项。

  CURLOPT_NOBODY: 如果你不想在输出中包含body部分,设置这个选项为一个非零值。

  CURLOPT_FAILONERROR: 如果你想让PHP在发生错误(HTTP代码返回大于等于300)时,不显示,设置这个选项为一人非零值。默认行为是返回一个正常页,忽略代码。

  CURLOPT_UPLOAD: 如果你想让PHP为上传做准备,设置这个选项为一个非零值。

  CURLOPT_POST: 如果你想PHP去做一个正规的HTTP POST,设置这个选项为一个非零值。这个POST是普通的 application/x-www-from-urlencoded 类型,多数被HTML表单使用。

  CURLOPT_FTPLISTONLY: 设置这个选项为非零值,PHP将列出FTP的目录名列表。

  CURLOPT_FTPAPPEND: 设置这个选项为一个非零值,PHP将应用远程文件代替覆盖它。

  CURLOPT_NETRC: 设置这个选项为一个非零值,PHP将在你的 ~./netrc 文件中查找你要建立连接的远程站点的用户名及密码。

  CURLOPT_FOLLOWLOCATION: 设置这个选项为一个非零值(象 "Location: ")的头,服务器会把它当做HTTP头的一部分发送(注意这是递归的,PHP将发送形如 "Location: "的头)。

  CURLOPT_PUT: 设置这个选项为一个非零值去用HTTP上传一个文件。要上传这个文件必须设置CURLOPT_INFILE和CURLOPT_INFILESIZE选项.

  CURLOPT_MUTE: 设置这个选项为一个非零值,PHP对于CURL函数将完全沉默。

  CURLOPT_TIMEOUT: 设置一个长整形数,作为最大延续多少秒。

  CURLOPT_LOW_SPEED_LIMIT: 设置一个长整形数,控制传送多少字节。

  CURLOPT_LOW_SPEED_TIME: 设置一个长整形数,控制多少秒传送CURLOPT_LOW_SPEED_LIMIT规定的字节数。

  CURLOPT_RESUME_FROM: 传递一个包含字节偏移地址的长整形参数,(你想转移到的开始表单)。

  CURLOPT_SSLVERSION: 传递一个包含SSL版本的长参数。默认PHP将被它自己努力的确定,在更多的安全中你必须手工设置。

  CURLOPT_TIMECONDITION: 传递一个长参数,指定怎么处理CURLOPT_TIMEVALUE参数。你可以设置这个参数为TIMECOND_IFMODSINCE 或 TIMECOND_ISUNMODSINCE。这仅用于HTTP。

  CURLOPT_TIMEVALUE: 传递一个从1970-1-1开始到现在的秒数。这个时间将被CURLOPT_TIMEVALUE选项作为指定值使用,或被默认TIMECOND_IFMODSINCE使用。

  下列选项的值将被作为字符串:

  CURLOPT_URL: 这是你想用PHP取回的URL地址。你也可以在用curl_init()函数初始化时设置这个选项。

  CURLOPT_USERPWD: 传递一个形如[username]:[password]风格的字符串,作用PHP去连接。

  CURLOPT_PROXYUSERPWD: 传递一个形如[username]:[password] 格式的字符串去连接HTTP代理。

  CURLOPT_RANGE: 传递一个你想指定的范围。它应该是"X-Y"格式,X或Y是被除外的。HTTP传送同样支持几个间隔,用逗句来分隔(X-Y,N-M)。

  CURLOPT_POSTFIELDS: 传递一个作为HTTP “POST”操作的所有数据的字符串。

  CURLOPT_REFERER: 在HTTP请求中包含一个"referer"头的字符串。

  CURLOPT_USERAGENT: 在HTTP请求中包含一个"user-agent"头的字符串。

  CURLOPT_FTPPORT: 传递一个包含被ftp "POST"指令使用的IP地址。这个POST指令告诉远程服务器去连接我们指定的IP地址。 这个字符串可以是一个IP地址,一个主机名,一个网络界面名(在UNIX下),或是'-'(使用系统默认IP地址)。

  CURLOPT_COOKIE: 传递一个包含HTTP cookie的头连接。

  CURLOPT_SSLCERT: 传递一个包含PEM格式证书的字符串。

  CURLOPT_SSLCERTPASSWD: 传递一个包含使用CURLOPT_SSLCERT证书必需的密码。

  CURLOPT_COOKIEFILE: 传递一个包含cookie数据的文件的名字的字符串。这个cookie文件可以是Netscape格式,或是堆存在文件中的HTTP风格的头。

  CURLOPT_CUSTOMREQUEST: 当进行HTTP请求时,传递一个字符被GET或HEAD使用。为进行DELETE或其它操作是有益的,更Pass a string to be used instead of GET or HEAD when doing an HTTP request. This is useful for doing or another, more obscure, HTTP request.

  注意: 在确认你的服务器支持命令先不要去这样做。

  下列的选项要求一个文件描述(通过使用fopen()函数获得):

  CURLOPT_FILE: 这个文件将是你放置传送的输出文件,默认是STDOUT.

  CURLOPT_INFILE: 这个文件是你传送过来的输入文件。

  CURLOPT_WRITEHEADER: 这个文件写有你输出的头部分。

  CURLOPT_STDERR: 这个文件写有错误而不是stderr。

  * curl_exec

  curl_exec -- 执行一个CURL会话

  描述

  bool curl_exec (int ch)

  在你初始化一个CURL会话,及为这个会话设置了所有的选项后,这个函数将被调用。它的目的仅仅是执行预先确定的CURL会话(通过给定的ch参数)。

  * curl_close

  curl_close -- 关闭一个CURL会话

  描述

  void curl_close (int ch)

  这个函数关闭一个CURL会话,并且释放所有的资源。CURL句柄(ch参数)也被删除。

  * curl_version

  curl_version -- 返回当前CURL版本

  描述

  string curl_version (void)

curl_version()函数返回一个包含CURL版本的字符串。

<&#63;php 
class MultiHttpRequest{ 
  public $urls = array(); 
  public $curlopt_header = 0; 
  public $cookie_file = ''; 
  public $collect_save_file = ''; 
  public $start_timestamp = ''; 
  public $end_timestamp = ''; 
  private $log_handle = ''; 
  private $collect_save_handle = ''; 
  private $db_conn = false; 
  private $pre_break_goods_id = ''; //上一次强制退出的id 
  private $per_break_brand_id = ''; //上一次更新到的brand_id 
  private $main_log_id = '';    //本次更新的主表日志id 
  private $start_time = ''; 
  public $login_session = ''; 
  public $date_char = ''; 
  private $mode = ''; 
  private $sql_log_handle = ''; 
  function __construct($upgrade_date='', $force_upt=false) 
  { 
     $this->mysql_init();   
     } 
    private function mysql_init(){ 
    $db_name = 'dbname'; 
    $db_user = 'name'; 
    $db_pass = 'pass'; 
    $db_host = 'localhost'; 
    $db_conn = mysql_connect($db_host, $db_user, $db_pass) ; 
    if(!$db_conn){ 
      echo '数据库连接失败!'; 
      exit; 
    } 
    $this->db_conn = $db_conn; 
    mysql_select_db($db_name); 
  } 
  public function init_login(){ 
    //第一步模拟登陆 
    $target_url = 'http://www.test.com/login.jsp'; 
    //post 提交的数据 
    $post_fields = array( 
    'username'  => '卓雅秀淘宝', 
    'password'  => 'joarshow.taobao.com', 
    't_url'    => '', 
    'Submit2'  => ' 登 录 ' 
    ); 
    //保存登陆的cookie 
    $cookie_file = dirname(__FILE__).'/cookie_'.time().'.txt'; 
    $this->cookie_file = $cookie_file; 
    //存cookie 
    $ch = curl_init($target_url); 
    curl_setopt($ch, CURLOPT_HEADER, 1); 
    //   curl_setopt($ch, CURLOPT_COOKIESESSION, 1); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); 
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); 
    $login_contents = curl_exec($ch); 
    curl_close($ch); 
  } 
  /** 
   * 测试 
   * 
   * @param unknown_type $test_url 
   */ 
  public function get_one_file($test_url){ 
    $ch = curl_init($test_url); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch,CURLOPT_COOKIE, $this->login_session); 
    curl_setopt($ch, CURLOPT_REFERER, 'http://www.test.com/welcome.shtml'); 
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)'); 
    $contents = curl_exec($ch); 
    curl_close($ch); 
    return $contents; 
  } 
  public function point_url_brand($url){ 
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch,CURLOPT_COOKIE, $this->login_session); 
    curl_setopt($ch, CURLOPT_REFERER, 'http://www.test.com/product.shtml'); 
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)'); 
    $contents = curl_exec($ch); 
    //   echo htmlspecialchars($contents);exit; 
    curl_close($ch); 
    return $contents; 
  } 
} 
Copy after login

使用CURL抓取淘宝页面集成方法

代码如下:

 /**
   * 根据地址抓取淘宝页面html代码
   * @param type $url 地址
   * @return boolean
   */
  public function getTaoBaoHtml($url) {
    if (empty($url)) {
      return false;
    }
    $ch = curl_init();
    // 设置 url
    curl_setopt($ch, CURLOPT_URL, $url);
    // 设置浏览器的特定header
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      "User-Agent: {Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0}",
      "Accept: {text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8}",
      "Accept-Language: {zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3}",
      "Cookie:{cq=ccp%3D1; cna=a7suCzOmSTECAXgg9iCf4AtX; t=671b2069c7e8ac444da66d664a397a5f; tracknick=%5Cu4F0D%5Cu6653%5Cu8F8901;
 _tb_token_=nDiU1vCuzFd0; cookie2=c54709ffbe04a5ccb80283c34d6b00fa; 
pnm_cku822=128WsMPac%2FFS4KgNn%2BYfhzduo4U2NC0zh9cAS4%3D%
7CWUCLjKhqr873bOIFQcMecSw%3D%7CWMEKRlV%
2B3D9a6XWaidNWNQOSWXwaXugvQHzhxALh%7CX0
YLbX78NUR2b2DHoxnIqZENQqR35TBZbfQ5vooI0b6GHZA3U1kr%7CXkdILog
Cr878ZK9I%2B%2FE3QjAD3lFJJaAZRA%3D%3D%7CXUeMwMR2s%
2BTUQk8IPP5TNgWfUjQwonccMCxihTa0fRYgtjgfa4j6%7CXMY
K7F8liOvH3hMUpzXkiaU%2FJw%3D%3D}",
    ));
    // 页面内容我们并不需要
    curl_setopt($ch, CURLOPT_NOBODY, 0);
    // 只需返回HTTP header
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // 返回结果,而不是输出它
    //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    ob_start();
    curl_exec($ch);
    $html = ob_get_contents();
    ob_end_clean();
    curl_close($ch);
    return $html;
  }
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

See all articles