本文操作环境: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的详细内容。