一次對HTTPS頁面抓取的報錯發現過程

今天發現系統後臺的某個抓取頁面忽然失效了,提示:javascript

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/.php

大概意思就是,在主線程裏使用同步的ajax請求對用戶體驗有影響,因此不讓用了。html

因而修改一下抓取函數:java

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("nowamagic.net");
	        }
	    }) 
	}

先是把async: false註釋掉,發現抓取依然是不行。照理這個是警告,不會阻止程序的運行纔對的。ajax

因而加上$.ajax的error選項,發現jqXHR.status輸出 200,就是網絡是通的。而jqXHR.responseText返回了一處PHP報錯,定位到錯誤處,發現$array file_get_contents($url); 報錯了。以前一直都是正常的,怎麼忽然報錯了呢?去那個網頁一看,發現網頁已經所有用上HTTPS了。json

如何讓抓取支持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就好了。app

打開phpinfo(),查看一下openssl是否已正常啓用,當正常啓用時,在OpenSSL support後面會出現enabled。curl

或者用下面的語句判斷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);

如今後臺抓取又從新正常,問題解決很容易,就是在發現問題上花的時間長了。

相關文章
相關標籤/搜索