Home > Net >  How to count role attributes from html page in python
How to count role attributes from html page in python

Time:02-24

is it possible to count how much time specific role shows up? There is a website and I want to use python to do this.

e.g

<div >
 <div role="grid">
  <div role="gridcell"></div>
  <div role="gridcell"></div>
  <div role="gridcell"></div>
 </div>
</div>

I want to count how much time "gridcell" shows up. I'm newbie so I don't know if this is possible if not can I just count how much "divs" are in <div role="grid">

I don't have much code to show just something basic

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
import keyboard

def show():
    if(keyboard.read_key() == "c"):
      #print(count_gridcell)
    
browser = webdriver.Chrome(ChromeDriverManager().install())
browser.get('https://www.example.com')

time.sleep(5)
show()

CodePudding user response:

Going by the DOM you have provided in the query:

If you want to count the role='gridcell' attributes:

gridcells = driver.find_elements(By.XPATH, "//div[@role='gridcell']")
print(len(gridcells))

If you wan to count the role that contains any role attribute that as grid in it (in this case - grid and gridcell:

grids = driver.find_elements(By.XPATH, "//div[contains(@role, 'grid')]")
print(len(grids))

If you want to count all the role attributes:

role_attrs = driver.find_elements(By.XPATH, "//*[@role]")
print(len(role_attrs))

Snapshots:

gridcell

any role containing grid

role

  • Related