0

我正在编写一个通用的网络爬虫,它从给定的网页获取主要内容(它必须爬取不同的页面)。

我尝试使用不同的工具来实现这一点,其中包括:

  • HtmlUnit : 爬行时返回给我太多的废料。
  • 本质:很多页面的重要信息都无法获取。
  • Boilerpipe:成功检索内容,几乎完美的结果,但是:

当我尝试抓取 TripAdvisor 之类的页面而不是给定的网页 html 时,它会返回以下消息:

我们注意到您使用的是不受支持的浏览器。Tripadvisor 网站可能无法正常显示。我们支持以下浏览器:Windows:Internet Explorer、Mozilla Firefox、Google Chrome。苹果电脑:Safari。

我正在使用用户代理: private final static String USER_AGENT = "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html)

我也尝试过使用不同的用户代理,甚至是移动的,但我总是得到同样的错误,它可能与 Javascript 有关吗?

如果需要,我的代码如下:

public void getPageName(String urlString) throws Exception {
        try (final WebClient webClient = new WebClient(BrowserVersion.BEST_SUPPORTED)) {
            boolean javascriptEnabled = true;

            webClient.setRefreshHandler(new WaitingRefreshHandler(TIMEOUT / 1000));
            webClient.setCssErrorHandler(new SilentCssErrorHandler());
            webClient.setJavaScriptErrorListener(new SilentJavaScriptErrorListener());
            webClient.getCache().setMaxSize(0);

            webClient.getOptions().setRedirectEnabled(true);
            webClient.getOptions().setUseInsecureSSL(true);
            webClient.getOptions().setJavaScriptEnabled(javascriptEnabled);
            webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.getOptions().setTimeout(TIMEOUT);
    
    //Boilerpipe // NOTE: Use ArticleExtractor unless DefaultExtractor gives better results for you
            URL  url = new URL(urlString);
            InputSource is = new InputSource();
            is.setEncoding("UTF-8");
            is.setByteStream(url.openStream());
            String text = DefaultExtractor.INSTANCE.getText(is);


            System.out.println("\n******************\n");
            System.out.println(text);
            System.out.println("\n******************\n");

            writeIntoFile(text);

        }
        catch (Exception e){
            System.out.println("Error when reading page  " + e);
        }
    }

4

1 回答 1

0

我们注意到您使用的是不受支持的浏览器。Tripadvisor 网站可能无法正常显示。我们支持以下浏览器:Windows:Internet Explorer、Mozilla Firefox、Google Chrome。苹果:Safari。

大多数网站都需要 javascript,通常这种消息表明您的代码不支持 javascript。

也许您必须再试一次 HtmlUnit。如果您对 HtmlUnit 有一些建议或错误报告,请随时在 github 上打开问题,我会尽力提供帮助。

于 2022-01-15T18:51:22.030 回答