今天發現系統後台的某個抓取頁面突然失效了,提示:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
Google了一下,大概意思就是,在主線程裡使用同步的ajax請求對用戶體驗有影響,所以不讓用了。
於是修改一下抓取函數:
function getProcessData(url)
{
$.ajax({
type: "get", //使用get方法訪問後台
dataType: "jsonp", //返回json格式的數據
jsonp:"callback",
url: '/news_spider_process/', // 跨域URL
//url: 'http://localhost/test.php', // 跨域URL
data:{"url":url},
//async: false,
//async: true,
error: function (jqXHR, exception) {
var msg = '';
//alert(jqXHR.status);
//alert(jqXHR.responseText);
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
//$('#content').html(msg);
},
success: function(data){
//alert(data.url);
$("#news_title").val(data.url);
//$("#title").html(data.url);
//$("#tagA").html("333");
re = new RegExp("\/p>","g");
$("#tagA").html(data.content.replace(re,"/p>\n"));
$("#news_creater").val("bkjia.com");
}
})
}
先是把async: false注釋掉,發現抓取依然是不行。照理這個是警告,不會阻止程序的運行才對的。
於是加上$.ajax的error選項,發現jqXHR.status輸出 200,就是網絡是通的。而jqXHR.responseText返回了一處PHP報錯,定位到錯誤處,發現$array file_get_contents($url); 報錯了。之前一直都是正常的,怎麼突然報錯了呢?去那個網頁一看,發現網頁已經全部用上HTTPS了。
如何讓抓取支持HTTPS呢?這裡環境是xampp,就以這個為例。
首先,檢查/xampp/php/ext目錄下是否存在php_openssl.dll文件,一般是有的,沒有就需要另行下載。
然後/xampp/php/php.ini文件,查找extension=php_openssl.dll,如果找到了,去掉前面的分號;如果沒找到就在extension=php_curl.dll的下一行添加如下代碼:extension=php_openssl.dll,然後重啟Apache就行了。
打開phpinfo(),查看一下openssl是否已正常啟用,當正常啟用時,在OpenSSL support後面會出現enabled。
或者用下面的語句判斷openssl的啟用情況:
$w = stream_get_wrappers();
echo 'openssl: ', extension_loaded ('openssl') ? 'yes':'no', PHP_EOL;
echo 'http wrapper: ', in_array('http', $w) ? 'yes':'no', PHP_EOL;
echo 'https wrapper: ', in_array('https', $w) ? 'yes':'no', PHP_EOL;
echo 'wrappers: ', var_export($w);
現在後台抓取又重新正常,問題解決很容易,就是在發現問題上花的時間長了。