CURL模拟登录、抓取页面数据

本文介绍使用PHP进行模拟登录及抓取登录后页面内容的方法。通过curl和phpQuery库,实现设置登录表单参数、获取并设置验证码hash、保存和读取cookie,完成对特定网站的模拟登录流程,并获取登录后的页面信息。
<?php

require('phpQuery-master/phpQuery/phpQuery.php');

try {

    //模拟登录表单Fields
    $post = [
        'username' => '100000',
        'password' => '123456',
        'submit' => '登录'
    ];

    $login_url = "http://www.test.com/User/Auth/login";

    \phpQuery::newDocumentFile($login_url);

    //引入hash
    $post['__hash__'] = pq('input[name="__hash__"]')->val();

    $cookie = dirname(__FILE__) . '/cookie.conf';

    $url = "http://www.test.com/User/Profile/index";

    //调用模拟登录
    login_post($login_url, $cookie, $post);

    //登录后,调用get_content()函数获取登录后指定的页面信息
    $content = get_content($url, $cookie);

    var_dump($content);
} catch (\Exception $exception) {
    var_dump($exception);
}

//file_put_contents('save.txt', $content); //保存抓取的页面内容

//模拟登录
function login_post($url, $cookie, $post)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    //301等重定向
    //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_exec($ch);
    curl_close($ch);
}

//用cookie获取登陆后链接界面
function get_content($url, $cookie)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
    //301等重定向
    //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    $rs = curl_exec($ch);
    curl_close($ch);
    return $rs;
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值