获取HTML字符串中标签的属性值
java中Document获取HTML字符串中的某一个标签的指定属性
String html = "<html><head><title>高克莱的一段html</title></head>"
+ "<body><h1>这是一段html</h1>"
+ "<p>点击网站名称访问网页</p>"
+ "<a href=\"https://www.baidu.com\">百度</a>"
+ "<a href=\"https://www.taobao.com\">淘宝</a>"
+ "<img src=\"img/1.jpg\"></img>"
+ "</body></html>";
Document doc = Jsoup.parse(html);
// 获取标签
//Elements links = doc.select("a");
// 获取带有指定属性的标签
Elements links = doc.select("img[src]");
// 遍历标签并获取属性值
for (Element link : links) {
String url = link.attr("src");
System.out.println("链接:" + url);
}
输出
链接:img/1.jpg
java中Document获取HTML字符串中的每一个标签的每个属性
String html = "<html><head><title>高克莱的一段html</title></head>"
+ "<body><h1>这是一段html</h1>"
+ "<p>点击网站名称访问网页</p>"
+ "<a href=\"https://www.baidu.com\">百度</a>"
+ "<a href=\"https://www.taobao.com\">淘宝</a>"
+ "<img src=\"img/1.jpg\"></img>"
+ "</body></html>";
Document doc = Jsoup.parse(html);
// 获取所有标签
Elements tags = doc.getAllElements();
// 遍历每个标签
for (Element tag : tags) {
System.out.println("Tag name: " + tag.tagName());
// 获取每个标签的属性
for (org.jsoup.nodes.Attribute attribute : tag.attributes()) {
System.out.println("Attribute: " + attribute.getKey() + " = " + attribute.getValue());
}
}
输出
Tag name: #root
Tag name: html
Tag name: head
Tag name: title
Tag name: body
Tag name: h1
Tag name: p
Tag name: a
Attribute: href = https://www.baidu.com
Tag name: a
Attribute: href = https://www.taobao.com
Tag name: img
Attribute: src = img/1.jpg
引用的包
org.jsoup.nodes.Document;
org.jsoup.Jsoup;
org.jsoup.select.Elements;
org.jsoup.nodes.Element;