【问题标题】:HtmlUnit xpath getElementHtmlUnit xpath getElement
【发布时间】:2014-01-07 02:23:11
【问题描述】:

我正在尝试为特定网站创建网络内容爬虫

http://v1000.vn/bang-xep-hang?ref=bang-xep-hang-1000-doanh-nghiep-dong-thue-thu-nhap-nhieu-nhat-2012

简而言之,我用来查找更改页面的链接(使用 javascript)的 XPath 无法正常工作,这会导致 NullPointExecetion。我尝试以各种方式修改 XPath,但没有任何效果。

另外,脚本运行后我是否需要运行任何方法来获取新页面?

> package gimasys.webService;

import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.ThreadedRefreshHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlLink;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class Crawlv1000 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        final WebCrawler wc = new WebCrawler();
        final PageCrawler pc = new PageCrawler();

        final WebClient webClient = new WebClient(BrowserVersion.CHROME_16);
        webClient.setRefreshHandler(new ThreadedRefreshHandler()); // This is to allow handling the page operation using threads else an exception will pop up
        try {
            HtmlPage page = webClient.getPage("http://v1000.vn/bang-xep-hang?ref=bang-xep-hang-1000-doanh-nghiep-dong-thue-thu-nhap-nhieu-nhat-2012");
            HtmlAnchor link = page.getFirstByXPath("//a[@href='javascript:loadRankingTable(3)']");
                        link.click();
                        System.out.println(page.getTextContent());

        } catch (FailingHttpStatusCodeException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        /*
        wc.crawl("http://v1000.vn/bang-xep-hang?ref=bang-xep-hang-1000-doanh-nghiep-dong-thue-thu-nhap-nhieu-nhat-2012");

        for (String url:wc.urlList)
        {
            pc.crawl(url);
        }
        */
    }
}

谢谢, 明阮

【问题讨论】:

    标签: java html xpath htmlunit


    【解决方案1】:

    亲爱的,你犯的非常小的错误,分号错误

    HtmlAnchor link = page.getFirstByXPath("//a[@href='javascript:loadRankingTable(3);']");
    link.click();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多