2
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?

wloszynski
  • 37
  • 6

2 Answers2

2

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']")))])
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Yes, I know. But can I somehow get the text of the anchor tags that are within my divs? I mean I wanted to do something like: divs.find_elements_by_tag_name('a'). But I can't do something like that, since I'm getting a huge error. – wloszynski Jul 03 '20 at 13:54
  • And what does that error say? Is it "AttributeError: 'list' object has no attribute 'find_elements_by_tag_name'? – Matt L. Jul 03 '20 at 14:02
  • Never mind, everything is working. Thank you very much. – wloszynski Jul 03 '20 at 14:23
1

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)
frianH
  • 7,295
  • 6
  • 20
  • 45