【发布时间】:2018-07-21 19:21:22
【问题描述】:
我正在使用 html_dom 抓取网站。
$url = $_POST["textfield"];
$html = file_get_html($url);
html_dom.php
function file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
// We DO force the tags to be terminated.
$dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText);
// For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done.
$contents = file_get_contents($url, $use_include_path, $context);
// Paperg - use our own mechanism for getting the contents as we want to control the timeout.
//$contents = retrieve_url_contents($url);
if (empty($contents) || strlen($contents) > MAX_FILE_SIZE)
{
return false;
}
// The second parameter can force the selectors to all be lowercase.
$dom->load($contents, $lowercase, $stripRN);
return $dom;
}
问题是,如果互联网连接太慢,它仍然会继续使用 file_get_html,那么它将是一个警告错误,提示无法打开流和致命错误:最大执行时间 30 秒。如果检测到警告错误,我尝试通过停止该功能来解决它:
function errHandle($errNo, $errStr, $errFile, $errLine) {
$msg = "Slow Internet Connection";
if ($errNo == E_NOTICE || $errNo == E_WARNING) {
throw new ErrorException($msg, $errNo);
} else {
echo $msg;
}
}
set_error_handler('errHandle');
但它仍然在执行时打印致命错误。关于如何解决这个问题的任何想法?
【问题讨论】:
-
你的标题有点误导;您真正需要的是在 GET 超时时如何处理错误情况。我没有做足够的 PHP 来知道如何在没有大量研究的情况下处理这个问题,但在 C# 中,我们只需将外部调用包装在 try..catch 块中。快速 Bing 搜索找到了这个例子:stackoverflow.com/a/17549618/73680。
-
试试 curl 或 guzzle。
标签: php html simple-html-dom