在下面的场景中,我们有一个 String
,它是来自任何页面的原始 HTML
(它可以根据需要更大),我们必须找到一些值(该 HTML
没有任何 Id
或 classes
)
在带有 html 代码的大型 String
中,我们必须提取一些值并将它们保存在变量中,在本例中为总学分值 (60)。
String response = "...
<BR>
<FONT COLOR="NAVY" FACE="ARIAL" SIZE="2">
<B>TOTAL CREDITS:</B>&NBSP; 60
</FONT>
<BR>
..."
提取该值的最佳方法是什么?
我所做的是识别一个唯一的前缀
,我在该点剪切字符串,然后剪切后缀
。
String value = response.split("TOTAL CREDITS:</B>&NBSP;")[1].split("</FONT>")[0].trim();
有更好的方法吗?
最佳答案
有特定的 API 用于从 java 解析 HTML 文件。
此链接可能是一个很好的起点 https://www.mkyong.com/java/jsoup-html-parser-hello-world-examples/
如果您使用 Maven,则必须包含依赖项
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
然后,您可以使用此代码作为起点,如您所见,使用 jsoup 将文档 DOM 作为文档加载,然后您可以使用与解析 xml 文件类似的方法来搜索 dom 元素:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
Document doc;
try {
// need http protocol
doc = Jsoup.connect("http://google.com").get();
// get page title
String title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
希望这有帮助
关于Java - 提取后缀和前缀中间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48944105/