Jsoup html 解析
Jsoup html parsing
<div id="footer">
<div class="row1"></div>
<div class="row2">
<div class="content">
<div class="row2col1">
<div class="moduletable">
<div class="custom">
<p>
<span style="color: #ffffff;"></span>
<span>
26
</span>
</p>
<p></p>
如何从 26 的第二个跨度中获取值?我试过了
Elements a = doc.select("div#footer div.row2 div.content div.row2col1 div.moduletable div.custom p");
for (int i = 1; i < a.size(); i++){
Element b = a.get(i);
if (i == 2){
if(isNum(b.text().trim())){
aw = b.text().trim();
}
else {
aw = "oops";
}
}
}
但它不起作用。谁能告诉我怎么做?
您的 CSS 查询 selects
<p> <span style="color: #ffffff;"></span> <span> 26 </span> </p>
<p></p>
如您所见,这是两个 <p>
元素,第一个是
<span style="color: #ffffff;"></span> <span> 26 </span>
第二个是空的。
如果您想要 select span
元素,您应该将其添加到您的查询中,例如
div#footer div.row2 div.content div.row2col1 div.moduletable div.custom p span
此外,如果您知道要获取第二个元素(索引为 1
,因为元素是从 0
索引的),您不需要循环,但可以简单地使用 a.get(1)
所以你的代码看起来更像这样
Elements a = doc.select("div#footer div.row2 div.content div.row2col1"
+ " div.moduletable div.custom p span");
// ^^^^^---add this part
String spanValue = a.get(1).text().trim();
if (spanValue.matches("\d+")) {// I changed this condition a bit just for tests
aw = spanValue;
} else {
aw = "oops";
}
<div id="footer">
<div class="row1"></div>
<div class="row2">
<div class="content">
<div class="row2col1">
<div class="moduletable">
<div class="custom">
<p>
<span style="color: #ffffff;"></span>
<span>
26
</span>
</p>
<p></p>
如何从 26 的第二个跨度中获取值?我试过了
Elements a = doc.select("div#footer div.row2 div.content div.row2col1 div.moduletable div.custom p");
for (int i = 1; i < a.size(); i++){
Element b = a.get(i);
if (i == 2){
if(isNum(b.text().trim())){
aw = b.text().trim();
}
else {
aw = "oops";
}
}
}
但它不起作用。谁能告诉我怎么做?
您的 CSS 查询 selects
<p> <span style="color: #ffffff;"></span> <span> 26 </span> </p>
<p></p>
如您所见,这是两个 <p>
元素,第一个是
<span style="color: #ffffff;"></span> <span> 26 </span>
第二个是空的。
如果您想要 select span
元素,您应该将其添加到您的查询中,例如
div#footer div.row2 div.content div.row2col1 div.moduletable div.custom p span
此外,如果您知道要获取第二个元素(索引为 1
,因为元素是从 0
索引的),您不需要循环,但可以简单地使用 a.get(1)
所以你的代码看起来更像这样
Elements a = doc.select("div#footer div.row2 div.content div.row2col1"
+ " div.moduletable div.custom p span");
// ^^^^^---add this part
String spanValue = a.get(1).text().trim();
if (spanValue.matches("\d+")) {// I changed this condition a bit just for tests
aw = spanValue;
} else {
aw = "oops";
}