我正在尝试解析http://whatismyip.com页面并获取我的位置(州和国家/地区)。数据似乎在<table class="table">
标签内,所以我正在寻找“表”。
但我得到一个错误Warning: file_get_contents(https://whatismyip.com): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in C:\xampp4\htdocs\scraping\libs\simple_html_dom.php on line 1081
无法弄清楚出了什么问题。
<?php
require_once('libs/simple_html_dom.php');
$html=new simple_html_dom();
$html->load_file('https://whatismyip.com');
$element=$html->find("table");
?>
答案 0 :(得分:3)
该网站正在检查请求的User-Agent
标头,但PHP没有发送任何标头(默认情况下)。你必须冒充&#34;冒充&#34;浏览器:
$context = stream_context_create(array(
'http' => array(
'header' => array('User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201'),
),
));
$html = file_get_contents('http://whatismyip.com/', false, $context);
// do what you want with the $html
更好(更快)的选择是为此使用一些库。我之前使用过GeoIP2-php,但我确定还有更多。
答案 1 :(得分:3)
基本上你的例子很好,但这里的错误是简单的html dom类不能使用Https所以尝试另一种方法
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_URL, "https://whatismyip.com");
curl_setopt($curl, CURLOPT_REFERER, "https://whatismyip.com");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201');
$str = curl_exec($curl);
curl_close($curl);
然后使用您的代码
$html->load_file($str);
$element=$html->find("table");
编辑添加用户代理以模拟真实的导航器(感谢ShiraNai7)
答案 2 :(得分:0)
尝试使用以下命令更改用户代理 -
{{1}}
它会正常工作!