php设置useragent的方法:1、用curl设置user_agent,代码如“curl_setopt($curl, CURLOPT_USERAGENT...)”;2、用file_get_contents设置user_agent。
本文操作环境:Windows7系统、PHP7.1版,DELL G3电脑
最近有在用PhpQuery,发现抓取一些网页的内容是空内容,询问了解到是设置了判断User Agent这个属性。于是一直在找PhpQuery怎么设置UserAgent,无奈PhpQuery文档太少,暂时没有找到,便去寻找PHP原生设置UserAgent的方法,找到了两种。
无User Agent代码:
<?php include 'phpQuery.php'; phpQuery::newDocumentFile('https://www.weiyiqi.net'); if(strstr(pq("")->html(),"mochoublog",false)) { echo "存在"; } else{ echo "不存在"; } ?>效果:
页面输出“不存在”有User Agent代码:
<?php include 'phpQuery.php'; ini_set('user_agent', 'Chrome 42.0.2311.135'); phpQuery::newDocumentFile('https://www.weiyiqi.net'); if(strstr(pq("")->html(),"mochoublog",false)) { echo "存在"; } else{ echo "不存在"; } ?>效果:
页面输出“存在”用curl设置user_agent:
$curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'http://www.baidu.com/'); curl_setopt($curl, CURLOPT_USERAGENT, 'Chrome 42.0.2311.135');//这里设置UserAgent为[Chrome 42.0.2311.135] $data = curl_exec($curl);//这里得到的是抓取的内容 curl_close($curl);用file_get_contents设置user_agent:
ini_set('user_agent', 'Chrome 42.0.2311.135');如果是用PhpQuery去抓取网页的话用第二种方法去设置UserAgent,方法一是无效的。但是如果你直接用curl去抓取网页的话当然是用方法一的“curl_setopt($curl, CURLOPT_USERAGENT,'Input user agent')”直接设置就好了。
推荐学习:《PHP视频教程》
以上就是php怎么设置useragent的详细内容!
查看更多关于php怎么设置useragent的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did51762
php怎么设置useragent
阅读:46次