如何使用jsoup解析HTML中的表格

24
<td width="10"></td>
<td width="65"><img src="/images/sparks/NIFTY.png" /></td> 
<td width="65">5,390.85</td>
<td width="65">5,428.15</td>
<td width="65">5,376.15</td>
<td width="65">5,413.85</td>

这是我需要提取值 5390.85、5428.15、5376.15 和 5413.85 的 HTML 源代码。我想使用 jsoup 来完成此任务,但我对 jsoup 相对较新(今天才开始使用)。那么我该如何做呢?

URL url = new URL("http://www.nseindia.com/content/equities/niftysparks.htm");
Document doc = Jsoup.parse(url,3*1000);
String text = doc.body().text();

我已经使用jsoup提取了网站的内容,但是如何提取我所需要的值呢?谢谢


2
发现另一个例子:http://technology.amis.nl/blog/13121/screenscraping-from-java-using-jsoup-effective-data-gathering-from-websites - 2sb
2个回答

33

试试这样做:

URL url = new URL("http://www.nseindia.com/content/equities/niftysparks.htm");
Document doc = Jsoup.parse(url, 3000);

Element table = doc.select("table[class=niftyd]").first();

Iterator<Element> ite = table.select("td[width=65]").iterator();

ite.next(); // first one is image, skip it

System.out.println("Value 1: " + ite.next().text());
System.out.println("Value 2: " + ite.next().text());
System.out.println("Value 3: " + ite.next().text());
System.out.println("Value 4: " + ite.next().text());

以下是打印输出内容:

Value 1: 5,390.85
Value 2: 5,428.15
Value 3: 5,376.15
Value 4: 5,413.85

6

以下是使用Groovy语言的示例:

def url = "http://www.espn.co.uk/scrum/rugby/match/scores/recent.html"
def doc = Jsoup.connec(url).get()

//Strip the table from the page
def table = doc.select("table").first()
// Strip the rows from the table
def tbRows = table.select("tr")

// For each column in a row, print its contents if not empty
tbRows.each { row ->
    def tbCol = row.select("td")
    tbCol.each { column ->
        if(!column.text().empty) {
            println column.text()
        }
    }
}

你可以将其保存到数组中以进行进一步处理。这只是另一个角度的观点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接