问题
I am trying to get the total number of items in an HTML page by a given class. I am using Selenium and Autohotkey to do it
I've searched a lot of this topic but haven't found my particular solution
Most of suggestions and answers I researched included solutions but for Java or other language, not for Autohotkey (Although they have similar structures in this case)
Using this code to work with:
<html>
<body>
<div id="pancakes">
<button class="button">Blueberry</button><br><br>
<button class="button">Banana</button><br><br>
<button class="button">Strawberry</button><br><br>
<button class="button">Yumi</button><br><br>
</div>
</body>
</html>
For getting the text from a element by class it can be done by this:
driver.findElementByClass("button").Attribute("innerText")
Output: Blueberry
Now, for getting a certain item of a class using Xpath, is as follows:
driver.findElementsByXpath("//*[contains(@id,'pancakes')]/button").item[1].Attribute("innerText")
Output: Strawberry
What I need is to get the total number of "buttons". So I need an output that gives me "4" (since there is 4 "buttons")
I havent find a way to do this in Autohotkey. I've seen solutions for other languages like
A
len(driver.find_elements_by_xpath('//a'))
B
WebElement webElement = driver.findElement(By.xpath("//form[@id='form1']/div[4]"));
//Get list of table elements using tagName
List<WebElement> list = webElement.findElements(By.tagName("table"));
C
IList<IWebElement> selectElements = driver.FindElements(By.TagName("select"));
foreach (IWebElement select in selectElements)
{
var selectElement = new SelectElement(select);
Console.WriteLine(selectElement.SelectedOption.Text);
}
and more but this doesn't work with Autohokey because of those functions and variables (like len(), IList, and others)
I am expecting to get just the total number of items by any way possible
I am thinking on maybe some function for Selenium I haven't founded yet and I dont know about (like some -at the end of the line- ".len",".size",".count" but non of them worked for me)
Any suggestions are welcome and appreciated, thanks!
EDIT: wow I was just missing the "()" on ".Count"
this is what I was looking for
driver.findElementsByXpath("//*[contains(@id,'pancakes')]/button").Count()
Thanks to supputuri
回答1:
You can use Count()
method to get the number of elements matching your xpath.
driver.findElementsByXpath("//*[contains(@id,'pancakes')]/button").Count()
you can refer to this for more information.
来源:https://stackoverflow.com/questions/57237659/how-to-get-the-total-number-of-elements-in-a-html-with-selenium-webdriver-and-au