[英]How to change color of a cell in HTML table using JSoup?
我需要使用 Java 和 Jsoup 解析一个表,并根据它的值更改单元格的颜色。 这就是 html 表的样子,也是需要定义单元格颜色的方式
<tr>
<td colspan="1">Test1</td>
<td colspan="1">JD</td>
<td colspan="1">N</td>
<td colspan="1">A</td>
</tr>
<tr>
<td>Test2</td>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td class="highlight-#fff0b3" title="Background color : Light yellow 100%" data-highlight-colour="#fff0b3">COLOR YELLOW</td>
<td class="highlight-#fff0b3" title="Background color : Light yellow 100%" data-highlight-colour="#fff0b3">YELL</td>
<td class="highlight-#fff0b3" title="Background color : Light yellow 100%" data-highlight-colour="#fff0b3">N/A</td>
<td class="highlight-#fff0b3" title="Background color : Light yellow 100%" data-highlight-colour="#fff0b3">N/A</td>
</tr>
我写了一个脚本,可以准备一个单元格的值并从中更改文本,但是我无法同时更改颜色
Document doc = Jsoup.parse(html);
Elements rows = doc.getElementsByTag("tr");
String status = "Pass"
for(Element row : rows) {
String Column1 = row.getElementsByTag("td").get(0).text();
if(Column1 == "MyValue"){
row.getElementsByTag("td").get(1).text("CustomValue");
row.getElementsByTag("td").get(2).text("CustomValue");
row.getElementsByTag("td").get(3).text("SomeValue");
if(status == "Pass"){ // Everything below doesn't work
row.getElementsByTag("td").get(1).class("highlight-#57d9a3");
row.getElementsByTag("td").get(2).class("highlight-#57d9a3");
row.getElementsByTag("td").get(3).class("highlight-#57d9a3");
row.getElementsByTag("td").get(1).title("Background color : Medium green 65%");
row.getElementsByTag("td").get(2).title("Background color : Medium green 65%");
row.getElementsByTag("td").get(3).title("Background color : Medium green 65%");
} else if(status == "Fail"){
row.getElementsByTag("td").get(1).class("highlight-#ff7452");
row.getElementsByTag("td").get(2).class("highlight-#ff7452");
row.getElementsByTag("td").get(3).class("highlight-#ff7452");
row.getElementsByTag("td").get(1).title("Background color : Medium red 85%");
row.getElementsByTag("td").get(2).title("Background color : Medium red 85%");
row.getElementsByTag("td").get(3).title("Background color : Medium red 85%");
} else{
//TBD
}
}
这是我得到的错误:
No signature of method: org.jsoup.nodes.Element.class() is applicable for argument types: (java.lang.String) values: [highlight-#57d9a3]
10:44:33 Possible solutions: clone(), clone(), addClass(java.lang.String), hasClass(java.lang.String), val(java.lang.String), getClass()
row.getElementsByTag("td").get(1)
返回一个Element
,它没有class
方法。
但是,它有一个classNames
方法,并且接受一个Set<String>
作为参数(即使您只需要传递一个类)。
所以你可以做类似的事情
row.getElementsByTag("td").get(1).classNames(Set.of("highlight-#57d9a3"));
等等。
除了那个编译错误, if(status == "Pass")
不是你在 java 中比较字符串的方式。 您需要执行类似if("Pass".equals(status))
的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.