首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我不能从这个网站上刮掉标题?

为什么我不能从这个网站上刮掉标题?
EN

Stack Overflow用户
提问于 2012-07-13 05:29:05
回答 3查看 445关注 0票数 3

我使用simple-html-dom从指定的站点上抓取标题。

代码语言:javascript
复制
<?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。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-07-13 05:39:17

这对我很有效:)

代码语言:javascript
复制
$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)));
}
票数 1
EN

Stack Overflow用户

发布于 2012-07-13 05:44:28

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

添加这个对我来说很有效:

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

票数 1
EN

Stack Overflow用户

发布于 2012-07-13 05:42:54

函数file_get_html在幕后使用file_get_contents。此函数可以从URL拉取数据,但要执行此操作,它需要发送一个User Agent字符串。

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

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

代码语言:javascript
复制
ini_set('user_agent','UA-String');

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11460972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档