Home > Back-end >  Python Selenium How to find elements by class name length
Python Selenium How to find elements by class name length

Time:03-23

Title is very explicative, i'm looking for every class in the page having a certain lenght.

Now i'm using

list=[] #empty array
elements = x.find_elements(By.XPATH,"//*[@class]") #finds out every element that have a class in the page, x is my chromedriver
for element in elements: #inspect every single element found
    class = element.get_attribute('class') #filters only the class name
    if (len(class)==8): #filters the class name exacy length
        list.append(element) #the element is now inside of the list and the loop can ispect next element

But this is VERY slow, i think it's because of the for loop. Have you got any idea on how to look for a specific lenght directly inside of the find_elements function or avoiding the for loop or any other solution to speed this up?

Thank you

CodePudding user response:

i'm just answering my own question because i think i found a very fast method to do it

i wanted to find classname "g" or "g <6alphanumerics>" for some reason in javascript if you make document.getElementsByClassName('g') it finds everything i needed

So the new snippet is:

classes = x.execute_script("return document.getElementsByClassName('g')")

the return is important otherwise the array will be empty

  • Related