简体   繁体   中英

Jsoup always returns null

I'm trying to pull data from a HTML String using Jsoup but without success. The HTML code is

<form>
<table>
    <tr>
        <th>First</th>
        <th>Second</th>
        <th>Third</th>
    </tr>
    <tr>
        <td><input type="text" name="elems[][f]" value="one" /></td>
        <td><input type="text" name="people[][s]" value="two" /></td>
        <td><input type="text" name="people[][t]" value="three" /></td>
    </tr>
    <tr>
        <td><input type="text" name="elems[][f]" value="one1" /></td>
        <td><input type="text" name="people[][s]" value="two2" /></td>
        <td><input type="text" name="people[][t]" value="three3" /></td>
    </tr>
</table>
<input type="submit" value="next" />

I've tried different cases, but nothing. I would retrieve data from th and every td. This is an example for "th":

Document document = Jsoup.parse(HTMLSTring);

    Elements tables = document.select("table");
    for (Element table : tables){
        Elements ths = table.getElementsByTag("th");
        for(Element th : ths)
        {
            System.out.println(th.text());
        }
    }

Your code works..

If you place your html input into a String variable like this :

public static void main(String[] args) {
    String HTMLSTring= "<form><table><tr><th>First</th><th>Second</th><th>Third</th></tr><tr><td><input type=\"text\" name=\"elems[][f]\" value=\"one\" /></td><td><input type=\"text\" name=\"people[][s]\" value=\"two\" /></td><td><input type=\"text\" name=\"people[][t]\" value=\"three\" /></td></tr><tr><td><input type=\"text\" name=\"elems[][f]\" value=\"one1\" /></td><td><input type=\"text\" name=\"people[][s]\" value=\"two2\" /></td><td><input type=\"text\" name=\"people[][t]\" value=\"three3\" /></td></tr></table><input type=\"submit\" value=\"next\" />";

    Document document = Jsoup.parse(HTMLSTring);
    Elements tables = document.select("table");
    for (Element table : tables){
        Elements ths = table.getElementsByTag("th");
        for(Element th : ths)
        {
            System.out.println(th.text());
        }
    }
}

You will have the expected result.

  • First
  • Second
  • Third

You may have an issue in the way you are reading the html input.

Put for example a breakpoint on Document document = Jsoup.parse(HTMLSTring); to be sure to receive the righ content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM