Home Backend Development PHP Tutorial curl实现站外采集的方法和技巧_php技巧

curl实现站外采集的方法和技巧_php技巧

May 17, 2016 am 08:50 AM
curl

选择curl的理由

关于curl与file_get_contents,摘抄一段通俗易懂的对比:
file_get_contents其实是一堆内置的文件操作函数的合并版本,比如file_exists,fopen,fread,fclose,专门提供给懒人用的,而且它主要是用来对付本地文件的,但又是因为懒人的原因,同时加入了对网络文件的支持;
curl是专门用来进行网络交互的库,提供了一堆自定义选项,用来应对不同的环境,稳定性自然要大于file_get_contents。

使用方法

1、开启curl支持

由于php环境安装后默认是没有打开curl支持的,需修改php.ini文件,找到;extension=php_curl.dll,把前面的冒号去掉,重启服务即可;

2、使用curl进行数据抓取

复制代码 代码如下:

// 初始化一个 cURL 对象
$curl = curl_init();
// 设置你需要抓取的URL
curl_setopt($curl, CURLOPT_URL, 'http://www.cmx8.cn');
// 设置header
curl_setopt($curl, CURLOPT_HEADER, 1);
// 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 运行cURL,请求网页
$data = curl_exec($curl);
// 关闭URL请求
curl_close($curl);

3、通过正则匹配找到关键数据

复制代码 代码如下:

//$data是curl_exec返回的的值,即采集的目标内容
preg_match_all("/
  • (.*?)/",$data, $out, PREG_SET_ORDER);
    foreach($out as $key => $value){
        //此处$value是数组,同时记录找到带匹配字符的整句和单独匹配的字符
        echo '匹配到的整句:'.$value[0].'
    ';
        echo '单独匹配到的:'.$value[1].'
    ';
    }
  • 技巧

    1、超时的相关设置

    通过curl_setopt($ch, opt) 可以设置一些超时的设置,主要包括:

    CURLOPT_TIMEOUT 设置cURL允许执行的最长秒数。
    CURLOPT_TIMEOUT_MS 设置cURL允许执行的最长毫秒数。 (在cURL 7.16.2中被加入。从PHP 5.2.3起可使用。 )
    CURLOPT_CONNECTTIMEOUT 在发起连接前等待的时间,如果设置为0,则无限等待。
    CURLOPT_CONNECTTIMEOUT_MS 尝试连接等待的时间,以毫秒为单位。如果设置为0,则无限等待。 在cURL 7.16.2中被加入。从PHP 5.2.3开始可用。
    CURLOPT_DNS_CACHE_TIMEOUT 设置在内存中保存DNS信息的时间,默认为120秒。

    复制代码 代码如下:

    curl_setopt($ch, CURLOPT_TIMEOUT, 60);   //只需要设置一个秒的数量就可以
    curl_setopt($ch, CURLOPT_NOSIGNAL, 1);    //注意,毫秒超时一定要设置这个
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);  //超时毫秒,cURL 7.16.2中被加入。从PHP 5.2.3起可使用

    2、通过post提交数据,保留cookie

    复制代码 代码如下:

    //以下摘抄一个例子过来,用于学习借鉴:
    //Curl 模拟登录 discuz 程序,适合DZ7.0

    !extension_loaded('curl') && die('The curl extension is not loaded.');   

    $discuz_url = 'http://www.lxvoip.com';//论坛地址   
    $login_url = $discuz_url .'/logging.php?action=login';//登录页地址   
    $get_url = $discuz_url .'/my.php?item=threads'; //我的帖子   

    $post_fields = array();   
    //以下两项不需要修改   
    $post_fields['loginfield'] = 'username';   
    $post_fields['loginsubmit'] = 'true';   
    //用户名和密码,必须填写   
    $post_fields['username'] = 'lxvoip';   
    $post_fields['password'] = '88888888';   
    //安全提问   
    $post_fields['questionid'] = 0;   
    $post_fields['answer'] = '';   
    //@todo验证码   
    $post_fields['seccodeverify'] = '';   

    //获取表单FORMHASH   
    $ch = curl_init($login_url);   
    curl_setopt($ch, CURLOPT_HEADER, 0);   
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   
    $contents = curl_exec($ch);   
    curl_close($ch);   
    preg_match('//i', $contents, $matches);   
    if(!empty($matches)) {   
        $formhash = $matches[1];   
    } else {   
        die('Not found the forumhash.');   
    }   

    //POST数据,获取COOKIE   
    $cookie_file = dirname(__FILE__) . '/cookie.txt';   
    //$cookie_file = tempnam('/tmp');   
    $ch = curl_init($login_url);   
    curl_setopt($ch, CURLOPT_HEADER, 0);   
    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);   
    curl_exec($ch);   
    curl_close($ch);   

    //带着上面得到的COOKIE获取需要登录后才能查看的页面内容   
    $ch = curl_init($get_url);   
    curl_setopt($ch, CURLOPT_HEADER, 0);   
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);   
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);   
    $contents = curl_exec($ch);   
    curl_close($ch);   

    var_dump($contents);
    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)

    How to realize the mutual conversion between CURL and python requests in python How to realize the mutual conversion between CURL and python requests in python May 03, 2023 pm 12:49 PM

    Both curl and Pythonrequests are powerful tools for sending HTTP requests. While curl is a command-line tool that allows you to send requests directly from the terminal, Python's requests library provides a more programmatic way to send requests from Python code. The basic syntax for converting curl to Pythonrequestscurl command is as follows: curl[OPTIONS]URL When converting curl command to Python request, we need to convert the options and URL into Python code. Here is an example curlPOST command: curl-XPOST https://example.com/api

    Tutorial on updating curl version under Linux! Tutorial on updating curl version under Linux! Mar 07, 2024 am 08:30 AM

    To update the curl version under Linux, you can follow the steps below: Check the current curl version: First, you need to determine the curl version installed in the current system. Open a terminal and execute the following command: curl --version This command will display the current curl version information. Confirm available curl version: Before updating curl, you need to confirm the latest version available. You can visit curl's official website (curl.haxx.se) or related software sources to find the latest version of curl. Download the curl source code: Using curl or a browser, download the source code file for the curl version of your choice (usually .tar.gz or .tar.bz2

    From start to finish: How to use php extension cURL to make HTTP requests From start to finish: How to use php extension cURL to make HTTP requests Jul 29, 2023 pm 05:07 PM

    From start to finish: How to use php extension cURL for HTTP requests Introduction: In web development, it is often necessary to communicate with third-party APIs or other remote servers. Using cURL to make HTTP requests is a common and powerful way. This article will introduce how to use PHP to extend cURL to perform HTTP requests, and provide some practical code examples. 1. Preparation First, make sure that php has the cURL extension installed. You can execute php-m|grepcurl on the command line to check

    PHP8.1 released: Introducing curl for concurrent processing of multiple requests PHP8.1 released: Introducing curl for concurrent processing of multiple requests Jul 08, 2023 pm 09:13 PM

    PHP8.1 released: Introducing curl for concurrent processing of multiple requests. Recently, PHP officially released the latest version of PHP8.1, which introduced an important feature: curl for concurrent processing of multiple requests. This new feature provides developers with a more efficient and flexible way to handle multiple HTTP requests, greatly improving performance and user experience. In previous versions, handling multiple requests often required creating multiple curl resources and using loops to send and receive data respectively. Although this method can achieve the purpose

    How to handle 301 redirection of web pages in PHP Curl? How to handle 301 redirection of web pages in PHP Curl? Mar 08, 2024 am 11:36 AM

    How to handle 301 redirection of web pages in PHPCurl? When using PHPCurl to send network requests, you will often encounter a 301 status code returned by the web page, indicating that the page has been permanently redirected. In order to handle this situation correctly, we need to add some specific options and processing logic to the Curl request. The following will introduce in detail how to handle 301 redirection of web pages in PHPCurl, and provide specific code examples. 301 redirect processing principle 301 redirect means that the server returns a 30

    what is linux curl what is linux curl Apr 20, 2023 pm 05:05 PM

    In Linux, curl is a very practical tool for transferring data to and from the server. It is a file transfer tool that uses URL rules to work under the command line; it supports file upload and download, and is a comprehensive transfer tool. . Curl provides a lot of very useful functions, including proxy access, user authentication, ftp upload and download, HTTP POST, SSL connection, cookie support, breakpoint resume and so on.

    How to set cookies in php curl How to set cookies in php curl Sep 26, 2021 am 09:27 AM

    How to set cookies in php curl: 1. Create a PHP sample file; 2. Set cURL transmission options through the "curl_setopt" function; 3. Pass the cookie in CURL.

    Solution to PHP Fatal error: Call to undefined function curl_setopt() Solution to PHP Fatal error: Call to undefined function curl_setopt() Jun 23, 2023 am 08:18 AM

    PHP is a widely used open source scripting language used by many websites. However, sometimes you may encounter the problem PHPFatalerror:Calltoundefinedfunctioncurl_setopt(), which may prevent your website from working properly. So what exactly causes this problem? In PHP, curl_setopt() is a very important function, which is used to extend the library through curl

    See all articles