gpt4 book ai didi

android - 如何使用 Jsoup for android 获取属性和值

转载 作者:行者123 更新时间:2023-11-28 04:00:32 24 4
gpt4 key购买 nike

如何使用带有 android 的 jsoup 从以下 html 代码中获取属性和值:

<div style='width:100px;height:100px;background:#d8a8d8'>&nbsp;</div> Actual Text <br>Text Inside br<br>
<div style='width:100px;height:100px;background:#dda0dd'>&nbsp;</div> This text Too.

我需要的是:

<强>1。两个 div 标签的背景值 -(即“d8a8d8”和“dda0dd”)

<强>2。 div 之后的文本-(即-“实际文本”和“This text Too.”)

<强>3。 br 标签之后的文本,紧跟在第一个 div 之后(即“Text Inside br”)

那么,我该怎么做呢?


我尝试的是:

  String st = "<div style='width:100px;height:100px;background:#d8a8d8'>&nbsp;</div> Actual Text <br>Text Inside br<br>
<div style='width:100px;height:100px;background:#dda0dd'>&nbsp;</div>";

Document doc = Jsoup.parse(s);
ements divs = doc.select("div");

for(Element elem : divs)
{
System.out.println(elem.html()); //get all elements inside div

String ss = elem.attr("style");
Log.d("logjsoup", "\n after Jsoup: " + ss);
}

我正在获取 div 样式中的所有值。

如何获得我想要的特定结果?

最佳答案

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupTest {

public static void main(String[] args) {
String html = "<div style='width:100px;height:100px;background:#d8a8d8'>&nbsp;</div> Actual Text <br>Text Inside br<br> \n"+
"<div style='width:100px;height:100px;background:#dda0dd'>&nbsp;</div> This text Too.";
//parse the html
Document doc = Jsoup.parse(html);
//select the divs
Elements divs = doc.select("div");
// use a regex matcher to get the background values
// pattern to look for all characters between "background:#" and "'"
Pattern p = Pattern.compile("(?<=background:#)(.*)(?=\")");
for(Element e: divs){
Matcher m = p.matcher(e.attributes().toString());
while(m.find()){
// background value
System.out.println(m.group());
}
// text after the div which is the next sibling of the div
System.out.println(e.nextSibling().toString().trim());
if(e.nextElementSibling()!= null){
// text after first br tag; the nextElementsibling returns the br element next sibling of this br is the text after br
System.out.println(e.nextElementSibling().nextSibling().toString());
}
System.out.println("-----------------------");
}
}
}

关于android - 如何使用 Jsoup for android 获取属性和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43237098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com