!!! Attention nécessite curl !!!!
Cette source permet de créer un mini crawler php pour récupérer des pages php qui peuvent nécessité un formulaire d'authentification.
Cette classe gère les cookies de session et permet aussi de changer l'identité du navigateur.
Il s'agit d'une classe que j'ai adapté d'une classe existante, mais je ne retrouve pas le liens de la version originale.
Les sources de la classes se trouvent dans le zip.
Petit conseil d'utilisation, pour faciliter la tache de vérification des variables transmises au serveur dans les formulaires, j'utilise l'outil de surveillance réseau de firebug.
Source / Exemple :
<?php
// Exemple d'utilisation sur le site de phpcs :)
include "classes/crawler.php";
/**
connexion et authentification
$myCrawler = new Crawler("phpcs", "true", "
http://www.phpcs.com/login.aspx",
/** formulaire d'authentification **/
array("_ASYNCPOST" => "true",
"__EVENTARGUMENT" => "",
"__EVENTTARGET" => "m\$CPH1\$LoginCS\$btnConnect",
"__LASTFOCUS" => "",
"__VIEWSTATE" => "/wEPDwUKLTk2MTMxMDA4Mw9kFgJmD2QWAgICEGRkFggCAw9kFgICAQ8WAh4HVmlzaWJsZWhkAgQPZBYEAgIPEA8WAh8AaGRkZGQCAw8PFgIfAGhkFgICAQ8QZGQWAGQCBQ9kFgJmD2QWCgICDw8WAh4PVmFsaWRhdGlvbkdyb3VwBRRjdGwwMF9DUEgxX0xvZ2luQ1NfdmRkAgMPDxYCHwEFFGN0bDAwX0NQSDFfTG9naW5DU192ZGQCBg8PFgIfAQUUY3RsMDBfQ1BIMV9Mb2dpbkNTX3ZkZAIHDw8WAh8BBRRjdGwwMF9DUEgxX0xvZ2luQ1NfdmRkAgsPZBYCZg9kFgRmDw8WBB8AZx4EVGV4dAU3RXJyZXVyIGxvcnMgZGUgbGEgc2Fpc2llIGRlIHZvdHJlIGxvZ2luIG91IG1vdCBkZSBwYXNzZWRkAgEPDxYCHwEFFGN0bDAwX0NQSDFfTG9naW5DU192ZGQCCQ9kFgICAQ8WAh8AaGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFG20kQ1BIMSRMb2dpbkNTJGNiUmVtZW1iZXJNZR+7aAhacpuYY8BQX2vS39YeG/8/",
"l" => "0",
/** mdp d'authentification **/
"m\$CPH1\$LoginCS\$tbPassword" => "mot de passe",
/** user d'authentification **/
"m\$CPH1\$LoginCS\$tbUserName" => "nom d'utilisateur",
"m\$SC1" => "m\$CPH1\$LoginCS\$upp|m\$CPH1\$LoginCS\$btnConnect",
"m\$UCTabsHome1\$DropSearch" => "tout",
"m\$UCTabsHome1\$txtSearch" => ""
)
);
/**
récupération d'une page get
$res = $myCrawler->http_fetch_url("
http://www.phpcs.com/default.aspx");
//affichage du resultat
echo $res;
/**
récupération d'une page post
$res = $myCrawler->http_post_url("
http://www.phpcs.com/default.aspx",
//formulaire post
array(
"__VIEWSTATE" => "/wEPDwULLTEzMzU1MjE5NzcPZBYCZg9kFgICAhBkZBYGAgMPZBYCAgEPFgIeB1Zpc2libGVoZAIED2QWBAICDxAPFgIfAGhkZGRkAgMPDxYCHwBoZBYCAgEPEGRkFgBkAgkPZBYCAgEPFgIfAGhkZNiqbZSK+5ynghDGsF2xMCr7KBF2"
,"l" => "0"
,"m\$UCTabsHome1\$DropSearch" => "tout"
,"m\$UCTabsHome1\$GGSearch" => "Rechercher"
,"m\$UCTabsHome1\$txtSearch" => "socket"
)
);
//affichage du resultat
echo $res;
?>
3 déc. 2009 à 15:17
Maintenant si tu as un problème vérifie que tu sois en php et surtout que tu ais le module CURL pour php
:
<?php
/**
* Crawler
* botcrawler
*
* @package Crawler
* @since 1.0
* @version $Revision: 1 $
*/
class Crawler {
var $USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14';
var $authentification_form;
var $authentification_url;
var $must_auth;
var $site_name;
var $cookies_path;
var $user_agent;
/**
* Constructor
*
* @param string $site_name name of site used for define the name of the cookie
* @param boolean $must_auth define if the site requiere an authenficiation - false by default,
* @param string $authentification_url url for authentification - empty by default
* @param array $authentification_form mixed value of the authenfication form
* @param string $user_agent set another user_agent
* @return void
*
*/function Crawler($site_name, $must_auth false, $authentification_url "", $authentification_form = array(), $user_agent = null, $debug = false) {
$this->user_agent = (!is_null($user_agent)?$user_agent:$this->USER_AGENT);
$this->site_name = $site_name;
$this->must_auth = $must_auth;
$this->authentification_url = $authentification_url;
$this->authentification_form = $authentification_form;
if (is_file("cookies/{$this->site_name}_cookie.txt")) {
unlink("cookies/{$this->site_name}_cookie.txt");
}
$fp_cookies = fopen("cookies/{$this->site_name}_cookie.txt", "w+");
fwrite($fp_cookies, '');
fclose($fp_cookies);
$this->cookies_path = realpath("cookies/{$this->site_name}_cookie.txt");
if ($this->must_auth) {
$ch = curl_init($authentification_url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $authentification_form);
curl_setopt($ch, CURLOPT_COOKIEFILE , $this->cookies_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookies_path);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_COOKIESESSION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent);
$ret = curl_exec($ch);
if ($ret === FALSE) {
die(curl_error());
}
if ($debug) echo "Debug :\n".print_r($ret, true)."
";
curl_close($ch);
if (preg_match('/(PHPSESSID=[0-9a-z,-]{32,40})/i', $ret, $m)) {
$sid = '?' . $m[1];
} else if (preg_match('#\'"\\\]+)"\s+value="([0-9a-z,-]{32,40})"\s*/?>#i', $ret, $m)) {
$sid = '?' . $m[1] . '=' . $m[2];
}
}
}
/**
* method to access to a page by get
*
* @param string $url
* @param integer $timeout
* @return content of page
*/
function http_fetch_url($url, $timeout = 1000)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_COOKIEFILE , $this->cookies_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookies_path);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_COOKIESESSION, false);
curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
/**
* method to access to a page by post
*
* @param stirng $url
* @param array $form array of string value of data post
* @param integer $timeout
* @return content of page
*/
function http_post_url($url, $form = array('none'=>'none'), $timeout = 1000)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIEFILE , $this->cookies_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookies_path);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($form));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_COOKIESESSION, false);
curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
}
?>
2 déc. 2009 à 22:33
Comme la classe crawler du php5 n'est pas installée sur les 2 serveurs restés en php4 je sais plus combien, il faut adapter et mettre des //devant public par exemple.
Les fonctions fetch et get de récupération des données n'étant pas reconnues, la seule possibilité est de les enlever, le code fonctionne.
Oui, mais voilà : ça passe sans erreur mais comme on ne récupère aucune donnée d'aucun site, on affiche une page blanche.
Il faut juste trouver le moyen de récupérer les données dans le fichier sample.php.
Une idée peut-être ?
merci
30 nov. 2009 à 14:59
Il semble que ta version de php ne gère pas les constante de classe.
Remplace
const USER_AGENT ...
//const USER_AGENT
et la ligne
$this->user_agent = (!is_null($user_agent)?$user_agent:Crawler::USER_AGENT);
par
$this->user_agent = (!is_null($user_agent)?$user_agent:'Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14');
30 nov. 2009 à 11:48
Idem pour mon compte professionnel chez Amen :
Parse error: parse error, unexpected T_CONST, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /home/.sites/69/siteX/web/monespace/crawler/classes/crawler.php on line 12
Alors, que faire ? si vous avez une solution, je suis preneur.
30 nov. 2009 à 09:49
Vous n'êtes pas encore membre ?
inscrivez-vous, c'est gratuit et ça prend moins d'une minute !
Les membres obtiennent plus de réponses que les utilisateurs anonymes.
Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.
Le fait d'être membre vous permet d'avoir des options supplémentaires.