我有一个合作伙伴创建了一些内容供我抓取。
我可以使用浏览器访问该页面,但是当尝试使用file_get_contents
,我得到一个403 forbidden
.
我尝试过使用stream_context_create
,但这没有帮助——可能是因为我不知道里面应该放什么。
1)有什么办法可以抓取数据吗?
2) 如果否,并且合作伙伴不允许配置服务器以允许我访问,那么我该怎么办?
我尝试使用的代码:
$opts = array(
'http'=>array(
'user_agent' => 'My company name',
'method'=>"GET",
'header'=> implode("\r\n", array(
'Content-type: text/plain;'
))
)
);
$context = stream_context_create($opts);
//Get header content
$_header = file_get_contents($partner_url,false, $context);
这不是您的脚本中的问题,而是您合作伙伴 Web 服务器安全性中的一个功能。
很难确切地说是什么阻碍了你,很可能是某种阻碍抓取的因素。如果您的合作伙伴可以访问他的网络服务器设置,这可能有助于查明。
您可以做的是通过设置用户代理标头来“伪造网络浏览器”,使其模仿标准网络浏览器。
我建议使用 cURL 来执行此操作,并且很容易找到执行此操作的良好文档。
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)