java - 如何在 HTML Java 中的较大元素中查找特定元素
问题描述
Document doc = Jsoup.parse(url1, 3*1000);
String subHead = "A h2 heading"; //note that at this point I have already parsed the html and found all the H2 headings and analysed them, But now I want to go further and analyse all H4 headings within the H2 section
print("Printing h4 titles of : " + subHead);
Elements sibHead; //variable that stores all elements between this H2 title and the next
String bodySelect = ("h2");
Elements kpageE = kpage.select(bodySelect);
for (Element e : kpageE) {
String estring = e.text();
print(estring + "--------------------------------------------");
if (estring.contentEquals(subHead)) {
sibHead = e.nextElementSiblings(); //this prints all elements in the h2 title section but i want only the h4 titles
for(Element ei : sibHead) {
String eistr = ei.text();
print(eistr);
}
}
我已经解析了 HTML 并得到了所有 H2 元素的列表,现在我想要一个 H2 元素和下一个 H2 元素之间的特定元素,更具体地说,我想要所有 H4 元素。
解决方案
使用 Jsoup,您可以使用 Document 类的 .getElementsByTag 方法,该方法允许您根据它们的 tagName 检索所有元素。
这是一个使用示例:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class App {
public static void main(String[] args) {
try {
Document doc = Jsoup.connect("https://inscription.devlab.umontp.fr/").get();
Elements h4elements = doc.getElementsByTag("h4");
for (Element h4 : h4elements) {
System.out.println(h4.text());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐阅读
- python - 将 DataFrame 重塑为 RNN Keras-tensorflow 的 3D 数组?
- shell - 如何从属性文件中进行变量替换并通过 Jenkinsfile 读取文件
- r - Group_by 表示 R 中的多列
- android - 如何修复警报管理器中的错误?
- ibm-cloud - Wix 网站上的 Watson Assistant Chatbot 集成
- python - Ansible 与 itertools 循环
- javascript - 如何防止图像隐藏在边框之外
- reactjs - React 组件与 Apollo graphQL useQuery 额外渲染
- sql - 如何正确查询 SQL 中复杂连接语句的结果?
- codeigniter - 登录codeigniter框架后如何留在上一页