简体   繁体   中英

Selenium Find Elements by Class Name Bug (Python)

Context: This block of code is supposed to click on a web element if it has the same name as the query and clicks the first web element otherwise.

Issue: If the else block is excluded, it works perfectly fine. Otherwise, it just defaults to the condition in the else block ( and then throws a stale element exception after the browser closes even though it already clicked on the element??? )

Reproducible: Absolutely, here's the file if needed https://github.com/The-Fag-Fajitas/Anime_Manager/blob/main/Back%20End/animemanager.py .

Note: Anything before this code works fine.

Note 2: The purpose of this code is to check for any similar names (ie x season 4 as opposed to x or x season 1 )

    # Only searches for the first 5 results
        an_list = dv.find_elements_by_class_name(desired_website.anime)[:5]
        for an in an_list:
            # Waits for the DOM to load (an implicit wait was already added).
            time.sleep(15)
            if an.text.lower() == query.lower():
                an.click()
            else:
                an_list[0].click()

What I think is happening is that you're getting a click which changes the page/dom. This renders everything in an_list a stale element.

So you either need to click into a new window (plenty of SO links to show how to do that) or break out of the for loop when you click what you want to click.

# Only searches for the first 5 results
an_list = dv.find_elements_by_class_name(desired_website.anime)[:5]
count=0;
while (count<len(an_list)):
    # Waits for the DOM to load (an implicit wait was already added).
    an = an_list[count]
    count = count+1;
    an_list = dv.find_elements_by_class_name(desired_website.anime)[:5]
    time.sleep(15)
    if an.text.lower() == query.lower():
        an.click()
    else:
        an_list[0].click()

Re find the an_list, as clicking on element changes the DOM reference

After bashing my head against the wall for two weeks, it finally worked. Problem is, I don't know how it works. For some reason, all stale element references suddenly disappeared and it works just fine. In fact, I found two solutions for it.

Solution 1:

an_list = dv.find_elements_by_class_name(desired_website.anime)
        for an in an_list:
            if an.text.lower() == query.lower():
                an.click()
        an_list[0].click()

Solution 2:

an_list = dv.find_elements_by_class_name(desired_website.anime)
        for an in an_list:
            if an.text.lower() == query.lower():
                an.click()
                break
        else:
            an_list[0].click()

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