【问题标题】:Scrape website for one data抓取一个数据的网站
【发布时间】:2014-04-21 15:10:18
【问题描述】:

我想从使用 JAVA (Android) 的网站中提取 <div class="score">4.1</div> 的值。我尝试了Jsoup,尽管它使用起来再简单不过,但它在 8 秒内给了我价值,这非常慢。您需要知道,该站点的页面源有 300,000 个字符,而这个 <div> 位于中间。

即使使用 HttpClient 并将源代码放入 StringBuilder 然后遍历整个字符串直到找到 score 部分也会更快(3-4 秒)。

我无法试用 HtmlUnit,因为它需要大量的 jar 文件,而且过了一段时间 Eclipse 总是在它的混乱中惹恼自己。

有没有更快的方法?

【问题讨论】:

    标签: java web-scraping


    【解决方案1】:

    您可以简单地发送一个 XMLhttpRequest,然后使用 search() 函数搜索响应。我认为这会更快。

    类似问题:Retrieving source code using XMLhttpRequest in javascript

    为了使搜索更快,您可以简单地使用 indexOf([sting to search],[starting index]) 并指定起始索引(它不需要非常准确,您只需减少搜索量区域)。

    【讨论】:

      【解决方案2】:

      这就是我所做的。问题是我逐行阅读网页,然后将它们粘合到StringBuilder 中并搜索特定部分。然后我问自己:为什么我要逐行阅读页面然后将它们粘在一起?因此,我将页面读入ByteArray 并将其转换为字符串。抓取时间不到一秒!

      try
          {
             InputStream is = new URL(url).openStream();
             outputDoc = new ByteArrayOutputStream();
             byte buf[]=new byte[1024];
             int len;
             while((len=is.read(buf))>0)
             {
                outputDoc.write(buf,0, len);
             }
             outputDoc.close();
              } catch(Exception e) {  e.printStackTrace(); }
      
      try {
          page = new String(outputDoc.toByteArray(), "UTF-8");
              //here I used str.indexOf to find the part
      
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-22
        • 1970-01-01
        • 2014-07-06
        • 1970-01-01
        • 2018-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多