简体   繁体   中英

How can I make selenium 'find_element' not be static?

I don't know If I expressed myself right, but my problem is I have this code:

def select_chat():
    driver.implicitly_wait(10)
    while True:
        chat_unread = driver.find_element_by_class_name('chat-drag-cover')
        chat_contains = chat_unread.get_attribute('innerHTML')
        if 'chat_unread' in chat_contains:
            chat_unread.click()

select_chat()

So this function should find multiple elements which contain 'chat unread', the problem is it does find the elements but it locks on one of them and doesn't go for the others, what can I do?

Lets have a look at whats happening in your code :

When you find_element_by_class_name('chat-drag-cover') the very first match (which is an WebElement ) is returned and gets stored within chat_unread . Example:

<selenium.webdriver.remote.webelement.WebElement (session="11a81cb13625b168f875de3b10dca3c5", element="0.3018415455432639-1")>

Next we are retriving the 'innerHTML' and storing it in chat_contains (which is a String ). Example:

Explore the life and work

Finally, we are trying to verify if 'chat_unread' in chat_contains: . Which is equivalent to :

If the String <selenium.webdriver.remote.webelement.WebElement (session="11a81cb13625b168f875de3b10dca3c5", element="0.3018415455432639-1")>

contains

Explore the life and work which is always False .

So click() is never called and we get back again to driver.find_element_by_class_name .

So the solution would be to use driver.find_elements_by_class_name("foo") which returns a list as follows :

chat_unread = driver.find_elements_by_class_name('chat-drag-cover')

Lastly, the WebElement itself eg chat unread must not be part of any validation but it's attributes should be used eg innerHTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM