我想使用 jsoup 解析此 HTML,但我需要在不使用“更改类名”类的情况下提取标题和副标题,因为类名总是在变化。我只需要来自“h1”属性和“p”的文本
HTML:
<header class="my header">
<div class="row">
<h3>I don't want this </h3>
<div class="Changing class name">
<h1>The headline </h1>
<p class=" my subtitle">
The subtitle
</p>
</div>
</div>
</header>
最佳答案
我们可以这样使用 getElementsByTag:
String MyTitle = doc.getElementsByTag("h1").get(0).text();
或者我们可以通过这种方式使用选择(工作更快):
String MyTitle = doc.select("my.header h1").first().text().trim();
关于副标题,我添加了一个检查以避免在字符串中输入 NULL:
Element Subtitle = doc.select("p.my").first();
if (Subtitle != null) {
String MySubtitle = doc.select("p.my").text().trim();}
关于java - 如何在不调用直接父级的情况下解析 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41697392/