我编写了以下方法,以便在网站上返回所有元素的对象。
public ArrayList<Person> getWantedFields() {
log.info("retrieve wanted fields");
resultList = new ArrayList<Person>();
List<WebElement> fullNames = driver.findElements(By.xpath("//div[@id='content_head_folge']/h1"));
List<WebElement> professions = driver.findElements(By.xpath("//div[@id='content_head_folge']/p"));
List<WebElement> streets = driver.findElements(By.xpath("//div[@id='content_head_folge']/p/br[1]"));
//2811 results
for (int i = 0; i < 2810; i++) {
resultList.add(new Person(fullNames.get(i).getText(), professions.get(i).getText(), streets.get(i).getText(), null, null, null, null, null)); //here I get the OutOfBounds exception
}
log.info(resultList.toString());
return resultList;
}
我猜2811显示的结果太多了。有没有办法迭代网站上的所有字段,而不知道它的大小?
感谢您的回复!
更新
使用
public ArrayList<Person> getWantedFields() {
log.info("retrieve wanted fields");
resultList = new ArrayList<Person>();
List<WebElement> fullNames = driver.findElements(By.xpath("//div[@id='content_head_folge']/h1"));
List<WebElement> professions = driver.findElements(By.xpath("//div[@id='content_head_folge']/p"));
List<WebElement> streets = driver.findElements(By.xpath("//div[@id='content_head_folge']/p/br[1]"));
//2811 results
for (int i = 0; i < fullNames.size(); i++) {
resultList.add(new Person(fullNames.get(i).getText(), professions.get(i).getText(), streets.get(i).getText(), null, null, null, null, null)); //here I get the OutOfBounds exception
}
log.info(resultList.toString());
return resultList;
}
我明白了:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at com.Test.service.PM.getFields(PM.java:152)
at com.Scraponator.gui.PersonLookup.main(PersonLookup.java:36)
答案 0 :(得分:1)
您可以使用列表的size()
:
for (int i = 0; i < fullNames.size(); i++) {
resultList.add(new Person(fullNames.get(i).getText(), professions.get(i).getText(), streets.get(i).getText(), null, null, null, null, null)); //here I get the nullpointer exception
}
答案 1 :(得分:1)
你在这里走在薄冰上。你怎么能确定所有三个列表都有相同的大小?如果有间隙(缺少子元素)怎么办?
List<WebElement> fullNames = driver.findElements(By.xpath("//div[@id='content_head_folge']/h1"));
List<WebElement> professions = driver.findElements(By.xpath("//div[@id='content_head_folge']/p"));
List<WebElement> streets = driver.findElements(By.xpath("//div[@id='content_head_folge']/p/br[1]"));
if( fullNames.size() != professions.size() || fullNames.size() != streets.size() ){
throw new IllegalStateException( "can't get the data" );
}