在jsoup中获取html字符串中的所有属性
问题描述:
我有HTML格式的字符串,我试图使用Jsoup获取所有属性及其值。在jsoup中获取html字符串中的所有属性
字符串是
String string=
"<button class=submit btn primary-btn flex-table-btn js-submit type=submit>Sign in</button>";
Document doc = Jsoup.parse(string);
try {
org.jsoup.nodes.Attributes attrs = doc.attributes();
for(org.jsoup.nodes.Element element : doc.getAllElements())
{
for(Attribute attribute : element.attributes())
{
System.out.println(attribute.getKey() + " --::-- "+attribute.getValue() );
}
}
} catch (Exception e) {
e.printStackTrace();
}
我期望的输出是::
key: **class** , Value is: **submit btn primary-btn flex-table-btn js-submit**
key: **type** , Value is: **submit**
但我得到的是这种
key: class , Value is: submit key: btn , Value is: key: primary-btn , Value is: key: flex-table-btn , Value is: key: js-submit , Value is: key: type , Value is: submit
这是因为引号的。如果我用
String string=
"<button class='submit btn primary-btn flex-table-btn js-submit' type='submit'> Sign in</button>";
我会得到我想要的输出。但我试图得到没有引号。
答
您不能不带引号,因为引号不是可选的。如果没有引号,那么您引用的HTML描述了一个元素,其中包含一个类(submit
)和一系列非类,无效的附加属性,名称如btn
,flex-table
等,这就是浏览器将如何解释它,就像JSoup所做的一样。如果这些要素是要素上的附加类别,则需要要求。
未引用属性值的语法
属性名称,后面的零个或多个空格字符,接着是单独的U + 003D等号字符,接着是零个或更多的空格字符,后面是属性值,除了上面给出的属性值的要求之外,不能包含任何字面空格字符,任何U + 0022 QUOTATIO (U + 003D)字符,“<”(U + 003C)字符,“>”(U + 003E)字符或U + 0060字符GRAVE ACCENT字符(`),并且不能是空字符串。
请注意,“一定不能包含任何文字空格字符”我强调的部分。
答
很简单与Jsoup
:
Document doc = Jsoup.parse(HTML);
List<String> tags = new ArrayList<String>(); //record tags
for(Element e : doc.getAllElements()){ // all elements in html
tags.add(e.tagName().toLowerCase()); // add each tag in tags List
//System.out.println("Tag: "+ e.tag()+" attributes = "+e.attributes()); // attributes with values in string
//System.out.println("Tag: "+ e.tag()+" attributes = "+e.attributes().asList()); //attributes in List<Attribute>
for(Attribute att : e.attributes().asList()){ // for each tag get all attributes in one List<Attribute>
System.out.print("Key: "+att.getKey()+ " , Value: "+att.getValue());
System.out.println();
}
}
System.out.println("*****************");
System.out.println("All Tags = "+tags);
System.out.println("Distinct Tags = "+ new HashSet<String>(tags));