0

我正在尝试从以下 url 获取表数据:

从此 URL 获取数据

我在 jaunt API 的帮助下编写了这段代码

package org.open.browser;

import com.jaunt.Element;
import com.jaunt.Elements;
import com.jaunt.JauntException;
import com.jaunt.UserAgent;

public class ICICIScraperDemo {

    public static void main(String ar[]) throws JauntException{
        
        UserAgent userAgent = new UserAgent();         //create new userAgent (headless browser)
        userAgent.visit("https://www.icicidirect.com/idirectcontent/Research/TechnicalAnalysis.aspx/companyprofile/inftec");     
       Elements links = userAgent.doc.findEvery("<div class=expander>").findEvery("<a>");  //find search result links
        String url = null;
        for(Element link : links) {
            if(link.innerHTML().equalsIgnoreCase("Company Details")){
                  url = link.getAt("href");
            }
        }
        /*userAgent = new UserAgent(); */        //create new userAgent (headless browser)
        userAgent.visit(url);   
        System.out.println(userAgent.getSource());
        Elements results = userAgent.doc.findEvery("<tr>").findEvery("<td>");
          System.out.println(results);
    }
}

但它没有用。

然后我尝试了另一个 APIhtmlunit并写了下面的代码

public void htmlUnitEx(){
        String START_URL = "https://www.icicidirect.com/idirectcontent/Research/TechnicalAnalysis.aspx/companyprofile/inftec";
                try {
                    WebClient webClient = new WebClient(BrowserVersion.CHROME);
                    HtmlPage page = webClient.getPage(START_URL);
                    WebResponse webres = page.getWebResponse();
                    //List<HtmlAnchor> companyInfo = (List) page.getByXPath("//input[@id='txtStockCode']");
                     HtmlTable companyInfo = (HtmlTable) page.getFirstByXPath("//table");
                        for(HtmlTableRow  item : companyInfo.getBodies().get(0).getRows()){  
                            String label = item.getCell(1).asText();
                            System.out.println(label);
                             if(!label.contains("Registered Office")){
                                    continue ;
                                }
}
}

但这也不给结果。

有人可以帮助如何在单个会话中从上述 url 和其他 Anchor url 获取数据吗?

4

1 回答 1

0

使用 HtmlUnit 你可以做到这一点

    String url = "https://www.icicidirect.com/idirectcontent/Research/TechnicalAnalysis.aspx/companyprofile/inftec";

    try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_60)) {
        HtmlPage page = webClient.getPage(url);
        webClient.waitForBackgroundJavaScript(1000);

        final DomNodeList<DomNode> divs = page.querySelectorAll("div.bigcoll");
        System.out.println(divs.get(1).asText());
    }

有两点要提:

  • 您必须在 getPage 调用后稍等,因为某些部分是由 javascript/AJAX 创建的
  • 有很多方法可以在页面上查找元素(请参阅查找特定元素)。我只做了一个快速破解来显示代码正在运行。
于 2018-09-07T18:31:42.983 回答