[英]jsoup hasClass returns wrong result
Help me please. 请帮帮我。 I using a jsoup lib and its method
hasClass
. 我使用一个jsoup lib及其方法
hasClass
。 Why Cur
returns "none!"? 为什么
Cur
返回“无!”? The source page: 源页面:
<body>
<div class="pagenav" data-role="vbpagenav" data-pagenumber="2" data-totalpages="223" data-address="showthread.php?t=650495&page=102" data-address2="" data-anchor="">
</div>
</body>
My code: 我的代码:
Document doc = null;
String result = "";
try {
doc = Jsoup.connect(params[0]).get();
Elements body = doc.select("body");
/* Navigation */
String Cur = "";
if (body.hasClass("pagenav")) {
Elements Current = body.select("div[data-pagenumber]");
String Cur1 = Current.attr("data-pagenumber");
int cur_page = Integer.parseInt(Cur1);
int next_page = cur_page + 1;
Cur = Integer.toString(next_page);
} else {
Cur = "none!";
}
result = body.html() + Cur;
} catch (IOException e) {
e.printStackTrace();
}
return result;
You are using the method hasClass
the wrong way. 您使用错误的方法
hasClass
方法。
In your selection you create a collection Elements body
that contains all the body
tags as Element
objects. 在您的选择中,您将创建一个包含所有
body
标签作为Element
对象的Elements body
Element
集合。
public boolean hasClass(String className)
will return a true
or false
as to whether any of your Element objects in your Elements body have the class name in their class attribute. 将返回关于您的Elements主体中的任何Element对象在其class属性中是否具有类名称的
true
或false
。 Here you will see what is wrong, since your collection Elements body
only contains all the body
tags, and not their child nodes. 在这里,您将看到问题所在,因为集合
Elements body
仅包含所有body
标签,而不包含其子节点。 None of your body
tags have their class attribute set to pagenav
, thus the hasClass()
method will return false
. 您的
body
标签没有一个将其class属性设置为pagenav
,因此hasClass()
方法将返回false
。
To solve your problem, you will need to create a new collection Elements
object for all the child nodes of the body
tags, and then check whether or not they have the class attribute set to pagenav
. 要解决您的问题,您将需要为
body
标签的所有子节点创建一个新的Collection Elements
对象,然后检查它们的class属性是否设置为pagenav
。
Selecting the body tag your way would require a double loop, such as 以您的方式选择主体标签将需要一个双循环,例如
Elements body = doc.select("body");
Elements bodyChildren = new Elements();
for (Element e : body) {
for (Element eChild : e.children()) {
bodyChildren.add(eChild);
}
}
if (bodyChildren.hasClass("pagenav")){...
Though, since you can only have one body tag, it can be more effective to select it straight away as follows 不过,由于您只能拥有一个身体标签,因此按以下方法立即选择它会更有效
Element body = doc.select("body").first();
Elements bodyChildren = new Elements();
for (Element e : body.children()) {
bodyChildren.add(e);
}
Both of above methods will return true
when you run hasClass()
on bodyChildren
. 在
bodyChildren
上运行hasClass()
时,上述两种方法都将返回true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.