Home  >  Article  >  Backend Development  >  为什么用curl或file_get_content抓取不到数据。解决方案

为什么用curl或file_get_content抓取不到数据。解决方案

WBOY
WBOYOriginal
2016-06-13 12:11:43997browse

为什么用curl或file_get_content抓取不到数据。

本帖最后由 xroha 于 2014-12-15 09:49:56 编辑 为什么用curl或file_get_content抓取不到数据。

百度经验里,比如http://jingyan.baidu.com/article/00a07f38441c3782d028dc04.html,
直接看页面源代码,是有文章数据。
但是用curl ,file_get_content.都无法正常获取文章内容。
这是为什么?已经伪造了IP,来路等,但还是抓取不到。百度是通过什么防止抓取数据的?

以下是代码:
<br />function fcontents( $url, $timeout = 5, $referer = "" ){<br />    $ch = curl_init();<br />    $header = array (<br />        'User-Agent: Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36','X-FORWARDED-FOR:154.125.25.15', 'CLIENT-IP:154.125.25.15'<br />    );<br />    curl_setopt($ch, CURLOPT_URL, $url);<br />    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);<br />    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br />    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //构造用户IP<br />    curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com/");//构造来路 <br />    $result = curl_exec($ch);<br />    curl_close($ch);<br />    return $result;<br />}<br /><br />$html = fcontents('http://jingyan.baidu.com/article/00a07f38441c3782d028dc04.html');<br /><br />echo $html;<br />

------解决思路----------------------
curl 只是抓取这个页面内容,但这个页面有其它许多的动态内容是不能通过抓取去填充的
------解决思路----------------------
没有cookie的原因吧。先把cookie加上。
$url = "http://jingyan.baidu.com/article/00a07f38441c3782d028dc04.html";<br />$cookie_jar = dirname(__FILE__)."/jy.cookie";<br /><br />/* 获取cookie */<br />$ch = curl_init();<br />curl_setopt($ch, CURLOPT_URL, $url);<br />curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br />curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);<br />curl_exec($ch);<br />curl_close($ch);


然后请求的时候带上cookie:
$ch = curl_init();<br />curl_setopt($ch, CURLOPT_URL, $url);<br />curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br />curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);<br />curl_setopt($ch, CURLOPT_HEADER, 0);<br />$res = curl_exec($ch);<br />curl_close($ch);<br />echo $res;
Statement:
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