【问题标题】:Get text from html tag using single class name, the html tag will contain multiple class使用单个类名从 html 标签获取文本,html 标签将包含多个类
【发布时间】:2014-07-10 07:57:27
【问题描述】:

我有一个 html 行,其中标签内有标签,一个标签包含多个类。我需要提取具有单个类名的文本(我只知道一个类名)

<p class="Body1"><span class="style3"></span><span class="style1">W</span><span class="Allsmall style5">extract this text </span><span class="style5">unwanted text </span></p>

我只知道类名 Allsmall 我想在 java 中使用 Jsoup 从 html 行中提取文本“提取此文本”。

【问题讨论】:

  • 用 HTML、CSS 或 Jsfiddle 等更多信息提出问题会更好理解。

标签: java html css jsoup


【解决方案1】:

您可以使用选择器语法根据其 CSS 类属性检索特定元素:

Document doc = Jsoup.parse(
  new File("input.html"), 
  "UTF-8", 
  "http://sample.com/");

Element allSmallSpan = doc.select("span.Allsmall").first(); // Retrive the first <span> element which belongs to "Allsmall" class

【讨论】:

  • 您是否更新了 sn-p 以使用您自己的 html 源代码?说NullPointerException 不会有太大帮助,请指出具体是哪一行?
  • 是的,我更改为我自己的代码 NullPointerException 来自Element allSmallSpan = doc.select("span.Allsmall").first();
  • 所以你的Document初始化有问题。我只能让它在本地使用包含您提供的

    内容的示例 html 文件。你能告诉我到目前为止你的Document 是如何初始化的吗?

  • (html = inputStream.readLine()) != null) Document doc = Jsoup.parse(html);Element allSmallSpan = doc.select("span.Allsmall").first();System.out.println(text.text());
  • NullPointerException 不是来自您提到的行,而是来自您正在读取跨度内容的行:text.text()(仍然找不到此变量的初始化位置),这是因为您正在逐行加载 html 文件,因此第一行将没有 span.Allsmall 元素,因此您将有一个空引用。您应该解析整个文件,而不是逐行解析。我要更新我的答案吗?
猜你喜欢
  • 1970-01-01
  • 2015-12-04
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-18
  • 1970-01-01
相关资源
最近更新 更多