【问题标题】:How can I parse specific info from html source code using Java如何使用 Java 从 html 源代码中解析特定信息
【发布时间】:2011-04-18 18:34:17
【问题描述】:

我知道我的问题有很多主题,但我找不到对我的答案有用的解决方案。我可以连接到网站并用 Java 逐行阅读,现在这是我的问题。我想从 html 页面解析特定信息。此页面包括 5 天的天气预报。例如预测标签的日期是这样的;

//date of forecast
< th id="ctl00_mpBody_thmGun1" class="arkaTrh">19 April< /th >

//Min weather:
< td id="ctl00_mpBody_thmMin1" class="minS">8< /td>

//Max weather
 < td id="ctl00_mpBody_thmMax1" class="maxS">17< /td>

second day and others tags continue like this,
< th id="ctl00_mpBody_thmGun2" class="arkaTrh">20 April< /th >
.
.
.

根据这些标签,我需要解析4月19日、17日和8日。

【问题讨论】:

标签: java html regex parsing web-scraping


【解决方案1】:

为了上帝的爱,不要使用正则表达式。我不知道这必须在 SO 上重复多少次。你最终会进入一个痛苦的世界。使用解析器,java 中有可用的负载。以下是其中一些:

Jericho

Dom4j

htmlparser

但还有几十个。只是谷歌“html parser java”或“java dom parser”之类的。请。

【讨论】:

  • 是的,我放弃了使用正则表达式,只是用 JSoup.Elements 解决了我的问题 link = doc.select("th[id=ctl00_mpBody_thmGun"+i+"]");
【解决方案2】:

你可以像这样制作一些正则表达式:

id="ctl00_mpBody_thmGun1"[^>]*?>(.*?)<

但是,如果您想要一个更强大的解决方案,最好清理 HTML 并使用 XPath 选择数据: http://www.ibm.com/developerworks/library/x-javaxpathapi.html

【讨论】:

    【解决方案3】:

    您可以使用HtmlUnit。它是为对网页进行单元测试而设计的,但您可以使用它来解析 HTML 代码。您可以使用以下方式获取预测数据:

    final WebClient webClient = new WebClient();
    final HtmlPage page = webClient.getPage("http://url.to.your.data");
    
    //get temperatures
    HtmlTableDataCell minTemp = page.getByXPath("//td[@class='minS']").get(0);
    HtmlTableDataCell maxTemp = page.getByXPath("//td[@class='maxS']").get(0);
    HtmlTableHeaderCell date = page.getByXPath("//th[@class='arkaTrh']").get(0);
    
    System.out.println("Forecast for " + date.asText() + " - Min: " + minTemp.asText() + ", Max: " + maxTemp.asText()); 
    

    【讨论】:

    • 在你告诉你需要使用正则表达式之前,我写了我的答案。我认为 HtmlUnit 比使用正则表达式更容易,但如果你需要它,那么我的答案不适合你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多