What are properties of find_element_by_class_name in selenium python?

Viewed 1216
browser = webdriver.Firefox()
browser.get(url)
divs = browser.find_elements_by_class_name('class')

Are there any properties of browser.find_element_by_class_name('class')?

For example if I have code like that:

<div class="foo">
    <a href="" class="poo">one</a>
    <a href="" class="poo">two</a>
    <a href="" class="poo">three</a>
</div>
<div class="foo">
    <a href="" class="koo">one</a>
    <a href="" class="koo">two</a>
    <a href="" class="koo">three</a>
</div>

I want to get text from 'a' tags. But firstly I want to get divs. so I do something like that:

divs = browser.find_elements_by_class_name('foo')

And now I want to get all the 'a' tags from my divs Array. Is it possible?

2 Answers

CLASS_NAME

CLASS_NAME is one of the Selenium supported Locator Strategy as well as a property of the WebElement interface which gets and sets the value of the class attribute of the specified element.

To get the texts from <a> tags with in parent <div> tags you can use either of the following Locator Strategies:

  • Using CLASS_NAME:

    print([my_elem.text for my_elem in WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "koo")))])
    
  • Using CSS_SELECTOR:

    print([my_elem.text for my_elem in WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.foo a.koo")))])
    
  • Using XPATH:

    print([my_elem.text for my_elem in WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='foo']//a[@class='koo']")))])
    

You can find elements in a element, extract them with nested loop:

divs = browser.find_elements_by_class_name('foo')

for div in divs:
    elements = div.find_elements_by_tag_name('a')
    for element in elements:
        print(element.text)
Related