2014-10-15 2 views
2

Я пытаюсь проанализировать строку, являющуюся HTML-страницей из страницы приложения моего браузера, для HTML-данных, которые я пытаюсь получить. (Короче говоря, я делаю некоторые веб-выскабливания результатов Google Images.)StringIndexOutOfBoundsException на очень большой строке

Моя функция, find(), кажется, работает очень хорошо для приличных строк, но в тот момент, когда она встречает полную строку, которая HTML кода, который я пытаюсь проанализировать, он жалуется на исключение StringIndexOutOfBoundsException. Вот функция моя находка(), и функция, которую я пытаюсь вызвать его из:

находки():

// helper functions 
    public static int find(String stringToFind, int startPos, String str) throws NullPointerException, 
     IllegalArgumentException 
    { 
     // make sure that neither argument is null and not an empty String 
     if ((stringToFind == null) || (str == null)) 
      throw new NullPointerException("null arguments are not allowed."); 
     if ((stringToFind.equals("")) || (str.equals(""))) 
      throw new IllegalArgumentException("String arguments must be non-empty."); 
     int position = startPos; 
     // while we are not at the end of the String and the stringToFind is not found 
     while (position != str.length()) 
     { 
      // find the first character in the string 
      position = str.indexOf(stringToFind.charAt(0), position+1); 
      // if found 
      if (position != -1) 
      { 
       int j = 0; 
       // search the other characters in str for the other characters in stringToFind 
       // while there is a character in str that matches its respective character in 
       // stringToFind and we are not at the end of either str,stringToFind 
       int firstCharacterPosition = -1; 
       while ((str.charAt(position) == stringToFind.charAt(j)) && 
         ((position < str.length()) && (j < stringToFind.length()))) 
       { 
        if (firstCharacterPosition == -1) 
         firstCharacterPosition = position; 
        // compare the next character in str with the next character in stringToFind 
        // if the characters match and the characters being matched is the last 
        // character in stringToFind 
        if ((str.charAt(++position) == stringToFind.charAt(++j)) && 
         (j == stringToFind.length() - 1)) 
         // we are done here 
         return firstCharacterPosition; 
       } 
      } 
      else break; 
     } 
     return -1; 
    } 

функция (s), который использует поиск():

public String getUserQuery() 
    { 
     // find the element in the HTML that starts with "<input id=\"gbqfq\"" and return it 
     index = find("<input id=\"gbqfq\"", index, searchPageHTML); 
     System.out.printf("index == %d", index); 
     try 
     { 
      return searchPageHTML.substring(index, 
       searchPageHTML.indexOf('>', index)); 
     } 
     catch (IndexOutOfBoundsException outOfBounds) 
     { 
      return ""; 
     } 
    } 

весь класс (который я передаю большой строку, которая является HTML-код):

import javax.swing.JFrame; 
import javax.swing.JEditorPane; 


public class SearchResultsHTMLParser 
{ 
    private String searchPageHTML; 
    private int index = -1; 
    public SearchResultsHTMLParser(String html) 
    { 
     this.searchPageHTML = html; 
     // setup a test GUI 
     JFrame frame = new JFrame("GoogleImageTest"); 
     JEditorPane editorPane = new JEditorPane("text/html", 
      this.getImagesDiv()); 
     frame.add(editorPane); 
     frame.pack(); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    // make methods that parse this.html for the user input and the images 
    /* The user input has an HTML id of "gbqfq", and the images all belong to the HTML class 
    * "rg_di". The function for the user input should return the value of the input field as a 
    * String, and the function for the images should simply return the substring that has all 
    * of the images in it. (This will be parsed further for each individual image.) 
    */ 
    public String getUserQuery() 
    { 
     // find the element in the HTML that starts with "<input id=\"gbqfq\"" and return it 
     index = find("<input id=\"gbqfq\"", index, searchPageHTML); 
     System.out.printf("index == %d", index); 
     try 
     { 
      return searchPageHTML.substring(index, 
       searchPageHTML.indexOf('>', index)); 
     } 
     catch (IndexOutOfBoundsException outOfBounds) 
     { 
      return ""; 
     } 
    } 

    /* This function will get the div with id="rg_s", and will probably not be used */ 
    public String getImagesDiv() 
    { 
     System.out.println("index == " + index); 
     index = find("<div id=\"rg_s\"", index, searchPageHTML); 
     System.out.println("index == " + index); 
     System.out.printf("charAt(%d) == %c", index, searchPageHTML.charAt(index)); 
     String startOfNextDiv = "<div jsl="; 
     int nextDivPos = find(startOfNextDiv, index, searchPageHTML); 
     // return the substring of searchPageHTML from the start of the found image div container 
     // to the end of it (it's ok if there is whitespace, so we could go up until the start of 
     // next div container) 
     return searchPageHTML.substring(index, nextDivPos); 
    } 

    // helper functions 
    public static int find(String stringToFind, int startPos, String str) throws NullPointerException, 
     IllegalArgumentException 
    { 
     // make sure that neither argument is null and not an empty String 
     if ((stringToFind == null) || (str == null)) 
      throw new NullPointerException("null arguments are not allowed."); 
     if ((stringToFind.equals("")) || (str.equals(""))) 
      throw new IllegalArgumentException("String arguments must be non-empty."); 
     int position = startPos; 
     // while we are not at the end of the String and the stringToFind is not found 
     while (position != str.length()) 
     { 
      // find the first character in the string 
      position = str.indexOf(stringToFind.charAt(0), position+1); 
      // if found 
      if (position != -1) 
      { 
       int j = 0; 
       // search the other characters in str for the other characters in stringToFind 
       // while there is a character in str that matches its respective character in 
       // stringToFind and we are not at the end of either str,stringToFind 
       int firstCharacterPosition = -1; 
       while ((str.charAt(position) == stringToFind.charAt(j)) && 
         ((position < str.length()) && (j < stringToFind.length()))) 
       { 
        if (firstCharacterPosition == -1) 
         firstCharacterPosition = position; 
        // compare the next character in str with the next character in stringToFind 
        // if the characters match and the characters being matched is the last 
        // character in stringToFind 
        if ((str.charAt(++position) == stringToFind.charAt(++j)) && 
         (j == stringToFind.length() - 1)) 
         // we are done here 
         return firstCharacterPosition; 
       } 
      } 
      else break; 
     } 
     return -1; 
    } 

    public static String getSubstringOf(String str, String subString, int pos) 
    { 
     // first, make a call to find(subString, pos, str) 
     int result = SearchResultsHTMLParser.find(subString, pos, str); 
     // return the substring if it exists, that is if find() != -1 
     return (result == -1) ? "" : subString; 
    } 

} 

Что я имею в виду делать

Я думал о преобразовании большой строки в большой полукокс [], а затем попытаться переписать свои функции, чтобы использовать это, блок за блоком. Я планирую это, потому что я думаю, что ошибка связана с максимальным размером String, который является HTML, для любого результата поиска Google Image, который длится сотни тысяч символов.

+0

Является ли эта ошибка из-за явного размер строки HTML? (Чтобы протестировать код, все, что вам нужно сделать, это дать ему HTML из результата поиска в Google Image.) –

+1

для меня это хаос. сузите раздел, который вас беспокоит. –

+0

Должен ли я для улучшения проверки включать код, который создает объект класса с переданным ему кодом HTML? –

ответ

0

Я нашел ошибку: по какой-то причине элементы, которые я искал, не существовали в моем Java-коде HTML. Это не имеет ничего общего с моей функции, и моя функция случилось сделать то же самое, как уже существующей функции, что я не был в курсе (до сих пор): http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,int)

System.out.println("Thanks, Kick Buttowski!!");

+0

Я изменил код на мою 'getUserQuery()' программу, потому что обнаружил, что тег HTML, который я пытался извлечь, был там, но в другом порядке атрибутов. Однако, с моим новым кодом, это похоже на то, что элемент все еще не существует !! Вот обновленный 'getUserQuery()': http://speedy.sh/pDGZe/getUserQuery.txt –

+0

У меня была такая же проблема при попытке очистить другой сайт. Оказывается, по какой-то причине HTML-код должен быть загружен, а затем файл должен быть прочитан, чтобы содержимое было найдено. По какой-то причине код HTML выглядит немного иначе как String в классе, чем печатается либо на экране, либо в файле. Что происходит, когда HTML-строки печатаются? –

Смежные вопросы