如何抓取登录受保护的页面?

时间:2013-02-06 14:46:28

标签: php

我想抓取网站搜索信息,我的脚本适用于普通网页,但如何抓取登录受保护的网页?我有登录信息我如何用网址发送此信息? 我的代码:

crawl_page("http://www.site.com/v3/search/results?start=1&sortCol=MyDefault");
function crawl_page($url) {
    $html = file_get_contents($url);
    preg_match_all('~<a.*?href="(.*?)".*?>~', $html, $matches);
    $str = "http://www.site.com/v3/features/id?Profile=";
    foreach($matches[1] as $newurl) {
       if (strpos($newurl, $str) !== false) {
        $my_file = 'link.txt';
        $handle = fopen($my_file, 'a') or die('Cannot open file:  '.$my_file);
        $numberNewline = $newurl  . PHP_EOL;
        fwrite($handle, $numberNewline);
       }
    }
}

任何帮助 感谢。

2 个答案:

答案 0 :(得分:1)

这在很大程度上取决于所使用的身份验证方法。最简单的是HTTP Basic Auth。对于该方法,您只需要构建一个这样的上下文:

$context = stream_context_create(array(
    'http' => array(
        'header'  => "Authorization: Basic " . base64_encode("$username:$password")
    )
));
$data = file_get_contents($url, false, $context);

这样,file_get_contents将使用HTTP基本身份验证。

其他auth方法可能需要更多工作,例如通过POST将密码发送到登录页面并存储会话cookie。

答案 1 :(得分:1)

我的回答仅适用于表单身份验证(这是最常见的身份验证形式)。

基本上,当您浏览网站时,会在其上打开“会话”。当您登录网站时,您的会话将获得“身份验证”,并且您将在此基础上获得访问权限。

由于存储在Cookie中的会话ID,您的浏览器会识别与服务器的对应会话。

因此,您必须浏览登录页面,然后浏览您想要的页面,而不会忘记在此过程中发送cookie。 Cookie是您浏览的所有页面之间的链接。

我实际上遇到了你前一段时间遇到的同样的问题,写了一个类来做这件事,而不必记住这个cookie。

快速查看课程,这并不重要,但请仔细阅读下面的示例。它允许您提交实现CSRF保护的表单。

这个类基本上具有以下功能: - 符合基于CSRF令牌的保护 - 发送“通用”用户代理。某些网站拒绝不通信用户代理的查询 - 发送Referrer标题。有些网站会拒绝不通信推荐人的查询(这是另一种反csrf保护) - 在通话中存储cookie

文件:WebClient.php

<?php
/**
 * Webclient
 *
 * Helper class to browse the web
 *
 * @author Bgi
 */

class WebClient
{
    private $ch;
    private $cookie = '';
    private $html;

    public function Navigate($url, $post = array()) 
    {
        curl_setopt($this->ch, CURLOPT_URL, $url);
        curl_setopt($this->ch, CURLOPT_COOKIE, $this->cookie);
        if (!empty($post)) {
            curl_setopt($this->ch, CURLOPT_POST, TRUE);
            curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post);
        }
        $response = $this->exec();
        if ($response['Code'] !== 200) {
            return FALSE;
        }
        //echo curl_getinfo($this->ch, CURLINFO_HEADER_OUT);
        return $response['Html'];
    }

    public function getInputs() 
    {
        $return = array();

        $dom = new DOMDocument();
        @$dom->loadHtml($this->html);
        $inputs = $dom->getElementsByTagName('input');
        foreach($inputs as $input)
        {
            if ($input->hasAttributes() && $input->attributes->getNamedItem('name') !== NULL)
            {
                if ($input->attributes->getNamedItem('value') !== NULL)
                    $return[$input->attributes->getNamedItem('name')->value] = $input->attributes->getNamedItem('value')->value;
                else
                    $return[$input->attributes->getNamedItem('name')->value] = NULL;
            }
        }

        return $return;
    }

    public function __construct()
    {
        $this->init();
    }

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

    private function init() 
    {
        $this->ch = curl_init();
        curl_setopt($this->ch, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1");
        curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($this->ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt($this->ch, CURLINFO_HEADER_OUT, TRUE);
        curl_setopt($this->ch, CURLOPT_HEADER, TRUE);
        curl_setopt($this->ch, CURLOPT_AUTOREFERER, TRUE);
    }

    private function exec() 
    {
        $headers = array();
        $html = '';

        ob_start();
        curl_exec($this->ch);
        $output = ob_get_contents();
        ob_end_clean(); 

        $retcode = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);

        if ($retcode == 200) {
            $separator = strpos($output, "\r\n\r\n");

            $html = substr($output, $separator);

            $h = trim(substr($output,0,$separator));
            $lines = explode("\n", $h);
            foreach($lines as $line) {
                $kv = explode(':',$line);

                if (count($kv) == 2) {
                    $k = trim($kv[0]);
                    $v = trim($kv[1]);
                    $headers[$k] = $v;
                }
            }
        }

        // TODO: it would deserve to be tested extensively.
        if (!empty($headers['Set-Cookie']))
            $this->cookie = $headers['Set-Cookie'];

        $this->html = $html;

        return array('Code' => $retcode, 'Headers' => $headers, 'Html' => $html);
    }

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

我该如何使用它?

在此示例中,我登录网站,然后浏览到包含上传文件的表单的页面,然后上传文件:

<?php
    require_once('WebClient.php');
    $url = 'http://example.com/administrator/index.php'; // This a Joomla admin

    $wc = new WebClient();
    $page = $wc->Navigate($url);
    if ($page === FALSE) {
         die('Failed to load login page.');
    }

    echo('Logging in...');

    $post = $wc->getInputs();
    $post['username'] = $username;
    $post['passwd'] = $passwd;

    $page = $wc->Navigate($url, $post);
    if ($page === FALSE) {
        die('Failed to post credentials.');
    }

  echo('Initializing installation...');

    $page = $wc->Navigate($url.'?option=com_installer');
    if ($page === FALSE) {
        die('Failed to access installer.');
    }

    echo('Installing...');

    $post = $wc->getInputs();
    $post['install_package'] = '@'.$file; // The @ specifies we are sending a file

    $page = $wc->Navigate($url.'?option=com_installer&view=install', $post);
    if ($page === FALSE) {
        die('Failed to upload file.');
    }

    echo('Done.');

Navigate()方法返回FALSE或浏览页面的HTML内容。

哦,最后一件事:不要使用正则表达式来解析HTML,这是错误的。有关于此的传奇StackOverflow答案:请参阅here

相关问题