gpt4 book ai didi

java - IndexOutOfBoundException - 从站点检索所有元素

转载 作者:行者123 更新时间:2023-12-02 05:33:51 25 4
gpt4 key购买 nike

我编写了以下方法来返回网站上所有元素的对象。

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)

最佳答案

你在这里如履薄冰。您如何确定所有三个列表的大小相同?如果存在间隙(缺少子元素)怎么办?

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" );
}

关于java - IndexOutOfBoundException - 从站点检索所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25230213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com