简单的html dom无法为网站打开流

差距

我正在尝试通过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");


    ?>
白奈7

该网站正在检查User-Agent请求标头,但PHP不发送任何请求(默认情况下)。您必须“模拟”浏览器:

$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,但我敢肯定还有更多。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章