我需要的是获取用户的搜索结果(每个用户作为一个具有名称、姓氏、标题等的对象),然后创建它们的列表并对它们执行一些操作。 我在返回一个对象以及该对象的列表及其名称时遇到问题。我总是得到最后一条记录,即使它正在遍历所有记录,即
(对象页面)
public User (WebElement elem) {
List<WebElement> titles = elem.findElements(By.xpath("//div[@id='userResults']//div[@class='title']"));
for (WebElement title: titles) {
setTitle(title.getText());
System.out.println(title.getText()); // everytime during iteration I am getting different title, which is good
}
System.out.println(titles.get(0).getText()); // ...but then I get the last index in the search result
}
setTitle 是一个 setter
public void setTitle(String title) {
this.title = title;
}
然后我创建 List<User>
我得到了相同标题的列表。可能出了什么问题?
最佳答案
不确定整个上下文,但也许您需要更改选择器。 您说您正在迭代特定用户。也许对于每个用户,您应该找到带有标题/名称或其他内容的特定嵌套元素并进行设置。我想我可能看起来像:
public User (WebElement elem) {
WebElement title = elem.findElement(By.xpath("//div[@class='title']")); // find nested element for specific user
setTitle(title.getText());
WebElement name = elem.findElement(By.xpath("//div[@class='name']"));
setName(name.getText());
// and so on...
}
或者也许:
public List<User> (WebElement elem) {
List<User> users = new ArrayList<>();
User user = new User();
List<WebElements> allElements = elem.findElements(By.xpath("//div[@class='userResults']"));
for (WebElement single: allElements ) {
WebElement title = single.findElement(By.xpath("//div[@class='title']"));
user.setTitle(title.getText());
WebElement name = single.findElement(By.xpath("//div[@class='name']"));
user.setName(name.getText());
users.add(user);
}
return users;
}
关于java - 创建对象时我只得到最后一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61428301/