What are properties of find_element_by_class_name in selenium python?

与世无争的帅哥 提交于 2021-02-05 07:40:28

问题


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?


回答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)



回答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']")))])
    


来源:https://stackoverflow.com/questions/62716634/what-are-properties-of-find-element-by-class-name-in-selenium-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!