2017-07-08 125 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

抱歉,评论你延迟。你的建议是我想要的这是工作非常感谢你! –