2017-07-08 51 views
0

我想用richtext來顯示html內容,所以我解析了url嘗試獲取<div class="margin-box"></div>中的所有內容爲String值。 但我無法解析網址。 代碼象下面這樣:Android使用JSoup解析HTML轉換爲字符串

用戶湯解析URL

Document document = Jsoup.parse(news_url); 
String news_content = CommonUtil.newsContent(document); 

數據捕獲

public static String newsContent(Document document){ 
 
     Elements elements = document.select("div.margin-box"); 
 
     String newsContent = elements.toString(); 
 
     return newsContent; 
 
    }

然後我得到調試結果: enter image description here

顯示URL解析不成功。 其實我想要得到像下面的值:

<div> 
 
<p> 
 
<imgsrc="http://p1.pstatp.com/large/1c67000332373537f0ff" img_width="640" img_height="360" inline="0" alt=「************」 onerror="javascript:errorimg.call(this);"> 
 
</p> 
 
<p class="pgc-img-caption」>***********</p><p>*************************************</p> 
 
<p><imgsrc="http://p3.pstatp.com/large/1c6e0000841ab42ca326" img_width="640" img_height="425" inline="0" alt=「**********」onerror="javascript:errorimg.call(this);"></p> 
 
<p class="pgc-img-caption」>********************************</p> 
 
<p><img src="http://p1.pstatp.com/large/1c6d00008eebccce3e2f" img_width="550" img_height="375" inline="0" alt=「************」 onerror="javascript:errorimg.call(this);"></p> 
 
<p class="pgc-img-caption」>*********</p><p>**************************</p><p>*********************</p><p>*****************</p></div>

我做了什麼錯?

全HTML BLOCK enter image description here

有DIV類中沒有元素 enter image description here

+0

您可以發佈網址或完整的html塊嗎? –

+0

好吧,我會編輯和添加完整的html塊 –

+0

@ProkashSarkari已添加完整的html塊 –

回答

1

這是第一次檢查時很有用,如果JSoup可以分析內容:http://try.jsoup.org/~8W0oCmiiYnFL01nUM6HDbQ9wwTA

你是使用Jsoup.parse其中expects html stored in a string。如果你想使用解析檢索,你必須pass a URL and a timeout的HTML源代碼:

String url = "http://servertrj.com/news/index/208"; 
Document doc = Jsoup.parse(new URL(url), 3000); 

大多數時候,你發現get()語法拉html源代碼,比較你的語法,這個簡單的例子:

String url = "http://servertrj.com/news/index/208"; 
String userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"; 
Document doc = Jsoup.connect(url).userAgent(userAgent).get(); 
Elements elements = doc.select(".margin-box"); 
System.out.println(elements.size() + "\n" + elements.toString()); 

輸出:

1 
<div class="margin-box"> 
<p style="margin: 0px 0px 15px; padding: 0px; border: 0px; line-height: 30px; font-family: &quot;Microsoft YaHei;, SimSun, Verdana, Arial; color: rgb(0, 0, 0); font-size: 15px;">[... truncated because of spam detection, but same as try.jsoup]</p> 
</div> 
+1

抱歉,評論你延遲。你的建議是我想要的這是工作非常感謝你! –