Reputation: 154
I'm web scraping a web site for a small project of mine and I want to get the number of faculty names.
The names are in the <tr>
tags under the <tbody>
tag.
I want to push the faculty names in to a list and right now I'm doing it with a hardcoded number of faculties that are currently on the site. That's ok for now, but the number might change and I want my code to work if they add more faculties.
var listOfFaculties = [];
for(var i = 2; i <= 18; i++){ // start with inedx 2 and go to 18 (from the first to the last faculty on the site) -- HARDCODED
await driver.findElement(By.xpath(getXPath(i))).getText().then(function(value) {
listOfFaculties.push({
Faculty: value
});
});
}
function getXPath(num){
return "//div[@id = 'main']/center[2]/font[@class='normal']/table/tbody/tr[" + num + "]/td[1]";
}
Is there a method to get the number of child nodes of <tbody>
tag? So I can put the number in to the for loop without hardcoding the bounds.
Upvotes: 0
Views: 256
Reputation: 2115
Use List of WebElement
to get the faculty length.
Your revised code should be like -
List<WebElement> elements = driver.findElements(By.xpath("//div[@id = 'main']/center[2]/font[@class='normal']/table/tbody/tr"));
var listOfFaculties = [];
for(var i = 2; i < elements.size(); i++){
await driver.findElement(By.xpath(getXPath(i))).getText().then(function(value) {
listOfFaculties.push({
Faculty: value
});
});
}
function getXPath(num){
return "//div[@id = 'main']/center[2]/font[@class='normal']/table/tbody/tr[" + num + "]/td[1]";
}
Upvotes: 1