2013-07-29 33 views
0

我使用Jsoup解析html文件並從元素中提取所有可見的文本。問題是javascript變量中有一些html位顯然被忽略。什麼是最好的解決方案來獲得這些數據?如何用Java中的Jsoup解析javascript變量中的html?

例子:

<!DOCTYPE html> 
<html> 
<head> 
    <script> 
     var html = "<span>some text</span>"; 
    </script> 
</head> 
<body> 
    <p>text</p> 
</body> 
</html> 

在這個例子中Jsoup只挑選了從p標籤這是它應該做的文本。我如何從var html跨度中獲取文本?該解決方案必須應用於數千個不同的頁面,所以我不能依賴像JavaScript變量具有相同名稱的東西。

+0

Atleast是否確定'html'內容位於雙引號內,且'

0

我不是很確定的答案,但我here以前看到類似的情況。

您可能可以使用Jsoup和手動解析來根據該答案獲取文本。

我只是修改的代碼爲您的具體情況:

Document doc = ... 
Element script = doc.select("script").first(); // Get the script part 


Pattern p = Pattern.compile("(?is)html = \"(.+?)\""); // Regex for the value of the html 
Matcher m = p.matcher(script.html()); // you have to use html here and NOT text! Text will drop the 'html' part 


while(m.find()) 
{ 
    System.out.println(m.group()); // the whole html text 
    System.out.println(m.group(1)); // value only 
} 

希望這會有所幫助。