我正在使用jsoup解析器,并试图进入span类并从中获取文本,但它返回的内容和大小总是为零。我已经粘贴了HTML源代码的一小部分。请帮我把课文提取出来。
<div class="list_carousel">
<div class="rightfloat arrow-position">
<a class="prev disabled" id="ucHome_prev" href="#"><span>prev</span></a>
<a class="next" id="ucHome_next" href="#"><span>next</span></a>
</div>
<div id="uc-container" class="carousel_wrapper">
<ul id="ucHome">
<li modelID="587">
<h3 class="margin-bottom10"><a href="/ford-cars/figo-aspire/" title="Ford Figo Aspire "> Ford Figo Aspire</a></h3>
<div class="border-dotted margin-bottom10"></div>
<div>Estimated Price: <span class="cw-sprite rupee-medium"></span> 5.50 - 7.50 lakhs</div>
<div class="border-dotted margin-top10"></div>
</li>
<li modelID="899">
<h3 class="margin-bottom10"><a href="/chevrolet-cars/trailblazer/" title="Chevrolet Trailblazer "> Chevrolet Trailblazer</a></h3>
<div class="border-dotted margin-bottom10"></div>
<div>Estimated Price: <span class="cw-sprite rupee-medium"></span> 32 - 40 lakhs</div>
<div class="border-dotted margin-top10"></div>
</li>我尝试了以下代码:
Elements var_1=doc.getElementsByClass("list_carousel");//four classes with name of list_carousel
Elements var_2=var_1.eq(1);//selecting first div class
Elements var_3 = var_2.select("> div > span[class=cw-sprite rupee-medium]");
System.out.println(var_3 .eq(0).text());//printing first result of span text如果你对我的内容不太清楚,请问我。提前谢谢。
发布于 2015-08-12 07:53:17
关于您的代码有几点需要注意:
A)您无法获得span的文本,因为它首先没有文本:
<div>Estimated Price:
<span class="cw-sprite rupee-medium"></span>
5.50 - 7.50 lakhs
</div>看见?文本在div中,而不是跨度!
( B)您的选择器"> div > span[class=cw-sprite rupee-medium]"并不是很健壮。HTML中的类可以按任意顺序出现,因此这两个类都可以
<span class="cw-sprite rupee-medium"></span>
<span class="rupee-medium cw-sprite"></span>是一样的。你的选择者只拿起第一个。这就是css中存在类语法的原因,您应该使用该类语法:
"> div > span.cw-sprite.rupee-medium"此外,如果你愿意的话,你可以先忽略他,>。
提出的解决方案
Elements lcEl = doc.getElementsByClass("list_carousel").first();
Elements spans = lcEl.select("span.cw-sprite.rupee-medium");
for (Element span:spans){
Element priceDiv = span.parent();
System.out.println(priceDiv.getText());
}发布于 2015-08-12 06:24:36
试一试
System.out.println(doc.select("#ucHome div:nth-child(3)").text());https://stackoverflow.com/questions/31957413
复制相似问题