php怎么设置useragent

来自:互联网
时间:2021-05-21
阅读:

最近有在用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')”直接设置就好了。

返回顶部
顶部