【问题标题】:why does "PHP Simple HTML DOM Parser" sometimes fail to parse an HTML body?为什么“PHP Simple HTML DOM Parser”有时无法解析 HTML 正文?
【发布时间】:2016-02-01 17:33:00
【问题描述】:

我正在使用的库是:PHP Simple HTML DOM Parser v1.5.0

对于一些 url,它的 str_get_html() 和 file_get_html() 调用将返回 false。例如:

 $html = HtmlDomParser::file_get_html('http://finance.yahoo.com/');

我该如何解决这个问题?

【问题讨论】:

  • 使用他们的财务 api 而不是抓取页面,问题解决了。
  • @Dagon,你假设我正在尝试抓取财务数据;但我想要做的是抓取页面 数据。另外,这只是我最近遇到的一个例子。其他网址也是如此。
  • 我强烈建议改用DOMDocument

标签: php simple-html-dom


【解决方案1】:

简单的 HTML DOM 解析器supports invalid HTML。 但问题可能在于加载 yahoo 页面,页面上的各种转发...... cURL 可以应对的一切。 如此快速、肮脏且可能最糟糕的处理这种情况的方法是使用变通方法 - 使用 cURL 加载页面内容,然后使用 Simple HTML DOM 的代码解析变量。

类似这样的:

<?php
include('simple_html_dom.php');

$search_url = 'http://finance.yahoo.com/';

function bCurl($url) {

    $cookie_file = "cookie1.txt";

    $header = array();
    $header[] = 'Accept: text/xml,application/xml,application/xhtml+xml,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: ';
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $result = curl_exec($ch);
    curl_close ($ch);

    return $result;
}

$result = bCurl($search_url);

$html = new simple_html_dom(); 
$html->load($result);   

$keywords = $html->find("meta[name=keywords]",0)->getAttribute('content');

print_r($keywords);
?>

正确的解决方案可能是分析 yahoo 财务页面,检查那里发生的情况,分析转发和反抓取机制、javascript 和 flash 对象......但是,我们都喜欢像这样的即时、快速和肮脏的解决方案,正确的? ;)

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多