如何加载HTML的全部内容-Jsoup

时间:2019-02-04 07:28:30

标签: java web-scraping jsoup

我试图使用jsoup下载html表行,但它仅解析部分html内容。我也尝试使用下面的代码来加载完整的html内容,但是不起作用。任何建议将不胜感激。

public class AmfiDaily {
    public static void main(String[] args) {
        AmfiDaily amfiDaily = new AmfiDaily();

        amfiDaily.extractAmfiTable("https://www.amfiindia.com/intermediary/other-data/transaction-in-debt-and-money-market-securities");
    }

    public  void extractAmfiTable(String url){
        Document doc;

        try {
            FileWriter writer = new FileWriter("D:\\FTRACK\\Amfi Report " + java.time.LocalDate.now() + ".csv");
            Document document = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
                    .maxBodySize(0)
                    .timeout(100000*5)
                    .get();

            Elements rows = document.select("tr");  

                 for (Element row : rows) {              

                Elements cells1 = row.select("td");                   

                for (Element cell : cells1) {

                    if (cell.text().contains(",")) {

                        writer.write(cell.text().concat(","));

                    }
                    else
                    {
                        writer.write(cell.text().concat(","));
                    }                       

                }                   

                writer.write("\n");                   
                 }
            writer.close();
        } catch (IOException e) {
            e.getStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

禁用JavaScript以准确查看Jsoup的内容。页面的一部分已加载AJAX,因此Jsoup无法访问它。但是,有一种简单的方法可以检查其他数据的来源。

您可以使用浏览器调试器检查“网络”选项卡,并查看请求和响应。

enter image description here

您可以看到该表是从以下URL下载的: https://www.amfiindia.com/modules/LoadModules/MoneyMarketSecurities

您可以直接使用此URL来获取所需的数据。

要克服Jsoup的限制并立即加载整个HTML,您应该使用Selenium Webdriver,例如:https://stackoverflow.com/a/54510107/9889778

相关问题