2

我想访问包含在 html 文件中的表。这是我的代码:

  import java.io.*; 
  import com.gargoylesoftware.htmlunit.html.HtmlPage;
  import com.gargoylesoftware.htmlunit.html.HtmlTable;
  import com.gargoylesoftware.htmlunit.html.*;
  import com.gargoylesoftware.htmlunit.WebClient;


  public class test {

  public static void main(String[] args) throws Exception {

    WebClient client = new WebClient();
    HtmlPage currentPage = client.getPage("http://www.mysite.com");
    client.waitForBackgroundJavaScript(10000);



final HtmlDivision div = (HtmlDivision) currentPage.getByXPath("//div[@id='table-matches-time']");

   String textSource = div.toString();
    //String textSource = currentPage.asXml();

FileWriter fstream = new FileWriter("index.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(textSource);

out.close();

    client.closeAllWindows();

  }

 }

表格是这样的:

   <div id="table-matches-time" class="">
                    <table class=" table-main">

但我收到此错误:

 Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlDivision
at test.main(test.java:20)

我怎样才能读到这张表?

4

3 回答 3

5

这有效(并返回给我一个 csv 文件;)):

    import java.io.*; 
    import com.gargoylesoftware.htmlunit.html.HtmlPage;
    import com.gargoylesoftware.htmlunit.html.HtmlTable;
    import com.gargoylesoftware.htmlunit.html.HtmlTableRow;
    import com.gargoylesoftware.htmlunit.html.*;
    import com.gargoylesoftware.htmlunit.WebClient;


    public class test {

    public static void main(String[] args) throws Exception {

    WebClient client = new WebClient();
    HtmlPage currentPage = client.getPage("http://www.mysite.com");
    client.waitForBackgroundJavaScript(10000);

FileWriter fstream = new FileWriter("index.txt");
BufferedWriter out = new BufferedWriter(fstream);



   for (int i=0;i<2;i++){

final HtmlTable table = (HtmlTable) currentPage.getByXPath("//table[@class=' table-main']").get(i);




   for (final HtmlTableRow row : table.getRows()) {

   for (final HtmlTableCell cell : row.getCells()) {
    out.write(cell.asText()+',');
   }
out.write('\n');
   }

   }

out.close();

    client.closeAllWindows();

   }

   }
于 2012-04-12T08:32:29.673 回答
0

看起来您的查询返回的是节点列表,而不是单个 div。您是否有多个具有该 ID 的项目?

于 2012-04-11T16:55:59.797 回答
0

替换这部分代码:

(HtmlDivision) currentPage.getByXPath("//div[@id='table-matches-time']");

和:

(HtmlDivision) currentPage.getFirstByXPath("//div[@id='table-matches-time']");

第一种方法总是返回一个元素的集合,即使它是一个,而第二种方法总是返回一个元素,即使有更多。

编辑:

由于您有两个相同的元素id(根本不建议这样做),因此您应该使用它:

(HtmlDivision) currentPage.getByXPath("//div[@id='table-matches-time']").get(0);

这样,您将获得集合的第一个元素。.get(1);会给你第二个。

于 2012-04-11T17:24:19.387 回答