gpt4 book ai didi

java - 我如何从 html 中获取细节?

转载 作者:行者123 更新时间:2023-11-29 03:44:46 25 4
gpt4 key购买 nike

我有一些 java 代码可以从我选择的网站打印出 html。我希望它只打印出如下所示的 HTML 代码中的特定日期:

<tr class="bgWhite">
<td align="center" width="50"><nobr>GD&#160;</nobr></td>
<td align="center">Q3&#160;2012</td>

<td align="left" width="*">Q3 2012 General Dynamics Earnings Release</td>
<td align="center">$ 1.83&#160;</td>
<td align="center">n/a&#160;</td>
<td align="center">$ 1.83&#160;</td>
<td align="center"><nobr>24-Oct-12</nobr></td>
</tr>
<tr class="bgWhite">
<td align="center" width="50"><nobr>GD&#160;</nobr></td>
<td align="center">Q2&#160;2012</td>

<td align="left" width="*">Q2 2012 General Dynamics Earnings Release</td>
<td align="center">$ 1.75&#160;</td>
<td align="center">n/a&#160;</td>
<td align="center">$ 1.79&#160;</td>
<td align="center"><nobr>25-Jul-12 BMO</nobr></td>
</tr>

所以我只想打印出来: 12 年 10 月 24 日 25-Jul-12

我该怎么做?

这是我的代码:

String nextLine;
URL url = null;
URLConnection urlConn = null;
InputStreamReader inStream = null;
BufferedReader buff = null;

try{
// Create the URL obect that points
// at the default file index.html
url = new URL("http://www.earnings.com/company.asp?client=cb&ticker=gd");
urlConn = url.openConnection();
inStream = new InputStreamReader(
urlConn.getInputStream());
buff= new BufferedReader(inStream);

// Read and print the lines from index.html
while (true){
nextLine =buff.readLine();
if (nextLine !=null){
System.out.println(nextLine);
}
else{
break;
}
}
} catch(MalformedURLException e){
System.out.println("Please check the URL:" +
e.toString() );
} catch(IOException e1){
System.out.println("Can't read from the Internet: "+
e1.toString() );
}

最佳答案

与低级 java.net.URLConnection 相比,使用功能齐全的 HTML 解析器更容易完成这项工作。然而,由于目标网站生成完全非语义的 HTML(一个和所有没有任何语义标识符/类的表,就像 90 年代网站的平均外观一样(讨厌)),即使是像样的 HTML 解析器也很难正确解析它。但无论如何,这是一个使用 Jsoup 的完整启动示例它准确地打印出您需要的信息:

Document document = Jsoup.connect("http://www.earnings.com/company.asp?client=cb&ticker=gd").get();
Elements dateColumn = document.select("table:eq(0) tr:eq(0) table:eq(7) tr:eq(2) table:eq(4) td:eq(6):not(.dataHdrText02)");

for (Element dateCell : dateColumn) {
System.out.println(dateCell.text());
}

就是这样。无需为低级 java.net.URLConnection 或冗长的 SAX 解析器而烦恼。

另见:

关于java - 我如何从 html 中获取细节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11511240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com