我正在嘗試使用this script從外部網站拉出一些文本。查找具有正則表達式和打印內容的特定div
它完美地工作,但它獲得整個頁面。我只想將特定div中的內容與類的「內容」相提並論。整個頁面放在變量「數據」裏面,那麼這個函數創建剝離一些標籤:
function filterData(data){
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
我怎麼會去用類「內容」找到div和裏面只有查看內容那?
更新:對不起,關於使用RegExes - 你能幫我在沒有使用RegEx的情況下獲取內容嗎?所以,這是我的HTML文件:
<a href="http://www.eurest.dk/kantiner/228/all.asp?a=9" class="ajaxtrigger">erg</a>
<div id="target" style="width:200px;height:500px;"></div>
<div id="code" style="width:200px;height:200px;"></div>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
if(url.match('^http')){
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
var tree = string2dom(data.results[0]);
container.html($("div.content", tree.doc));tree.destroy();
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
}
);
} else {
$('#target').load(url);
}
}
function filterData(data){
return tree;
}
});
</script>
你爲什麼要使用正則表達式解析HTML?特別是在使用JavaScript的瀏覽器中,這是完全不必要的,您可以使用DOM。 – Tomalak
同時,在星球上的Sane:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Johnsyweb
是的,好吧,似乎我不應該使用RegEx來執行此操作。事情是,我的JavaScript技能非常有限,而且我發現的代碼使用了RegEx,所以這就是我使用它們的原因。 但我會嘗試使用DOM。謝謝! – hoegenhaug