Heim  >  Artikel  >  Backend-Entwicklung  >  CURL 模拟登陆并获取数据 博客分类: 开发

CURL 模拟登陆并获取数据 博客分类: 开发

巴扎黑
巴扎黑Original
2016-11-09 11:10:591131Durchsuche

在做采集程序时,有时我们要抓取一些登录才能访问的页面。但是有时即使我们登录成功了,却还是无法抓取相关页面,这是为什么呢?

    嗯,最有可能的原因是没把登录成功后的 cookie 一并传递过去。

    对于一些安全防范措施不是做得很高的网站,我们可以通过 PHP 的函数 curl_setopt 来登录的。

<?php
//在指定目录中建立一个具有唯一文件名的文件。如果该目录不存在,tempnam() 会在系统临时目录中生成一个文件,并返回其文件名。 
$cookie_file = tempnam(&#39;./tmp&#39;,&#39;cookie&#39;);//其中 cookie 为文件名的前缀
$postfield = &#39;LoginForm[username]=admin&LoginForm[password]=admin&LoginForm[rememberMe]=0&yt0=Login&#39;;
$url = "http://localhost/testdrive/index.php?r=site/login";//登录 提交的 url,可以通过 firfox 的 firebug 工具或者 google chrome 的开发人员工具来查看
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);//保存 cookie 的文件
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postfield);
$strlen = curl_exec($ch);
$url = "http://localhost/testdrive/index.php";//访问登录后的页面。
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);//再次发送请求时,cookie 就会自动传递过去
$strlen = curl_exec($ch);
?>


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn