为什么我不能把标题从这个网站上刮下来


Why can I not scrape the title off this site?

我使用简单的html dom从指定网站上刮下标题。

<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.pottermore.com/');
foreach($html->find('title') as $element) 
       echo $element->innertext . '<br>';
?>

我尝试过的任何其他网站都有效,比如apple.com。

但如果我输入pottermore.com,它不会输出任何内容。Pottermore上有flash元素,但我试图去掉标题的主屏幕没有flash,只有html。

这对我有效:)

$url = 'http://www.pottermore.com/';
$html = get_html($url);
file_put_contents('page.htm',$html);//just to test what you have downloaded
echo 'The title from: '.$url.' is: '.get_snip($html, '<title>','</title>');
function get_html($url)
{
    $ch = curl_init();
    $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
    $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    $header[] = "Cache-Control: max-age=0";
    $header[] = "Connection: keep-alive";
    $header[] = "Keep-Alive: 300";
    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $header[] = "Accept-Language: en-us,en;q=0.5";
    $header[] = "Pragma: "; //browsers keep this blank.  
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows;U;Windows NT 5.0;en-US;rv:1.4) Gecko/20030624 Netscape/7.1 (ax)');
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIE);
    curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIE); 
    $result = curl_exec ($ch);
    curl_close ($ch);
    return($result);
}
function get_snip($string,$start,$end,$trim_start='1',$trim_end='1')
{
    $startpos = strpos($string,$start);
    $endpos = strpos($string,$end,$startpos);
    if($trim_start!='')
    {
        $startpos += strlen($start);
    }
    if($trim_end=='')
    {
        $endpos += strlen($end);
    }
    return(substr($string,$startpos,($endpos-$startpos)));
}

只是为了确认别人在说什么,如果你不发送用户代理字符串,这个网站会发送403 Forbidden。

添加这个对我有效:

用户代理:Mozilla/5.0(Windows;U;Windows NT 5.0;en-US;rv:1.4)Gecko/20030624 Netscape/7.1(ax)

函数file_get_html使用隐藏的file_get_contents。此函数可以从URL中提取数据,但要这样做,它会发送一个用户代理字符串。

默认情况下,此字符串为空。一些网络服务器利用这一事实来检测非浏览器正在访问其数据,并选择禁止这样做。

您可以在php.ini中设置user_agent来控制发送的用户代理字符串。或者,你可以试试:

ini_set('user_agent','UA-String');

'UA-String'设置为您喜欢的任何值。