我有一个 HTML block ,我正在使用 Jsoup 解析,但是,并不是所有的都是相关的,解析不相关的部分会丢弃我的数据集。
在网站上,有一个标题可以随时更改。此 header 中有链接,但我不关心这些链接。当 Jsoup 解析文档时,它会将这些想法添加到我的链接数组中并丢弃我的值。
我感兴趣的 HTML 出现在
<!-- BEGIN TOPICS -->
标签。
我希望能够告诉 Jsoup 忽略该标签上方的所有内容。这可能吗?如果没有,我可以通过在文档底部开始解析来解决这个问题,但我也不确定我将如何处理。
我的 Jsoup 查询如下。请忽略所有注释掉的行和调试语句,我已经尝试解决这个问题一段时间了,但仍然有测试代码。
Thread getTitlesThread = new Thread() {
public void run() {
TitleResults titleArray = new TitleResults();
StringBuilder whole = new StringBuilder();
try {
URL url = new URL(
Constants.FORUM);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(new BufferedInputStream(urlConnection.getInputStream())));
String inputLine;
while ((inputLine = in.readLine()) != null)
whole.append(inputLine);
in.close();
} catch (IOException e) {}
finally {
urlConnection.disconnect();
}
} catch (Exception e) {}
Document doc = Parser.parse(whole.toString(), Constants.FORUM);
Elements threads = doc.select("TOPICS > .topic_title");
Elements authors = doc.select("a[hovercard-ref]");
// for (Element author : authors) {
// authorArray.add(author.text());
// }
// cleanAuthors();
if (threads.isEmpty()) {
Log.d("POC", "EMPTY BRO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!11");
}
// for (Element thread : threads) {
// titleArray = new TitleResults();
// Log.d("POC", thread.toString());
//
// titleArray.setAuthorDate(authorArray.get(0));
// authorArray.remove(0);
//Thread title
// threadTitle = thread.text();
// titleArray.setItemName(threadTitle);
//
// //Thread link
// String threadStr = thread.attr("abs:href");
// String endTag = "/page__view__getnewpost"; //trim link
// threadStr = new String(threadStr.replace(endTag, ""));
// threadArray.add(threadStr);
// results.add(titleArray);
// }
}
};
getTitlesThread.start();
最佳答案
根据您的描述,这应该有效(如果没有实际的 HTML 输入,很难确定):
Document document = ...;
Elements elements = document.getAllElements();
Element comment = null;
int size = elements.size();
for (int i = 0; comment == null && i < size; i++) {
Element element = elements.get(i);
for (Node node : element.childNodes()) {
if (node instanceof Comment) {
String str = ((Comment) node).getData().trim();
if ("BEGIN TOPICS".equals(str)) {
comment = element;
break;
}
}
}
}
// Did we find <-- BEGIN TOPICS -->?
if (comment != null) {
// You can now select from the siblingElements of comment
// and only get stuff "after" that comment:
// e.g. Elements e = comment.siblingElements().select("a");
} else {
// Oh snap.
}
关于java - Jsoup 在指定标签后开始解析还是从页面底部开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8742797/