jsoup屬性選擇器跟jquery的寫法一致。
1.在 QueryParser類中有定義的屬性匹配規則 private static final String[] AttributeEvals = new String[]{"=", "!=", "^=", "$=", "*=", "~="}
調用select方法的時候,寫法還是有點區別的
select("body > div[class*='top']")
在匹配的時候,"=", "!=", "^=", "$=", "*=", 會忽略[class*='xx']中的單引號或者反斜槓,也就是可以正確匹配
public abstract static class AttributeKeyPair extends Evaluator {
String key;
String value;
public AttributeKeyPair(String key, String value) {
Validate.notEmpty(key);
Validate.notEmpty(value);
this.key = key.trim().toLowerCase();
if (value.startsWith("\"") && value.endsWith("\"")
|| value.startsWith("'") && value.endsWith("'")) {
value = value.substring(1, value.length()-1);
}
this.value = value.trim().toLowerCase();
}
}
只有"~=",不會忽略[class~=‘xx’]中的單引號或者反斜槓。再用它寫正則表達式的時候一定要注意不要多寫單引號。
public AttributeWithValueMatching(String key, Pattern pattern) {
this.key = key.trim().toLowerCase();
this.pattern = pattern;
}
2.Jsoup中的:lt(),:gt(),:eq(),:nth-child()等通過索引來選取元素,索引值都是它所在同級元素中索引位置,只有nth-child索引從1開始,其他的從0開始
以EQ的源碼爲示例:
public static final class IndexEquals extends IndexEvaluator {
public IndexEquals(int index) {
super(index);
}
@Override
public boolean matches(Element root, Element element) {
return element.elementSiblingIndex() == index;
}
@Override
public String toString() {
return String.format(":eq(%d)", index);
}
}