[英]how to store webtable in java collection hashmap or hashset or arraylist?
在我的用戶個人資料頁面上的應用程序中,用戶具有:
Name: XYZ
Age: ##
Address: st.XYZ
等等...
當缺少一個元素(例如年齡)時,另一行會取代它,因此我無法對元素的xpath
進行硬編碼。 我想要的是:
我想(打印)提取整個表數據並與實際比較。 因此,當我要求“名稱”作為鍵時,應在其前面給出單元格值作為鍵的值。
我嘗試了什么:我能夠獲得將td
固定的tr
標簽元素的文本。 但是對於另一個用戶,當缺少某行時,它將失敗或給出錯誤的值。
for (int i = 2; i < 58; i++) {
String actor_name = new WebDriverWait(driver, 30).until(ExpectedConditions
.elementToBeClickable(By.xpath(first_part+i+part_two))).getText();
System.out.print("\n"+"S.no. "+(i-1)+" "+actor_name);
try {
driver.findElement(By.xpath(first_part+i+part_two)).click();
new WebDriverWait(driver, 30).until(ExpectedConditions
.elementToBeClickable(By.partialLinkText("bio"))).click();
//driver.findElement(By.partialLinkText("bio")).click();
} catch (Exception e) {
// TODO: handle exception
System.out.println("Not a link");
}
Thread.sleep(5000);
System.out.print(" "+driver.findElement(By.xpath("//*[@id='overviewTable']/tbody/tr[3]/td[2]")).getText());
driver.get("http://www.imdb.com/title/tt2310332/fullcredits?ref_=tt_cl_sm#cast");
}
上面的代碼對於此頁面上的前3名演員可以正常使用,但由於在生物學頁面上沒有缺少任何一行,因此排名第四。
在生物頁面上,表中的兩列具有屬性,其他具有其值。 我想使用key
為key
(屬性為左列的value
)及其value
右列的值的鍵值對進行集合。 這樣我就可以通過提及屬性值來自由獲取值。
我正在使用JAVA編寫腳本。
您是否可以嘗試以下代碼,並在有任何疑問的情況下向我提出任何疑問?
driver.get("http://www.imdb.com/title/tt2310332/fullcredits?ref_=tt_cl_sm#cast");
String height = "";
String actorName = "";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
List<WebElement> lstUrls = driver.findElements(By
.xpath("//span[@itemprop='name']/..")); // all a tags
List<String> urls = new ArrayList<>();
for (WebElement webElement : lstUrls) {
urls.add(webElement.getAttribute("href")); // saving all hrefs attached in each a tag
}
Map<String, String> actorHeightData = new HashMap<String, String>();
for (String string : urls) {
driver.get(string);
actorName = driver.findElement(
By.xpath(".//*[@id='overview-top']/h1/span")).getText(); // Getting actor's name
driver.findElement(By.xpath("//a[text()='Biography']")).click(); // Clicking Biography
try {
height = driver.findElement(
By.xpath("//td[.='Height']/following-sibling::td"))
.getText(); // Getting height
} catch (NoSuchElementException nsee) {
height = ""; // If height not found
}
actorHeightData.put(actorName, height); // Adding to map
}
您可以使用所需的所有可空字段創建PersonData類。 但是不能使用空獲取器。
例如
calss PersonData{
private String name;
public getName(){
if(name == null)
return "";
return name;
}
}
並將所有人員存儲在列表中。
在您的頁面中,您將要求人員輸入字段,並且始終在表的單元格中有內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.