Home > other >  How to make my loop check the if statement until the condition is met / basically until the button a
How to make my loop check the if statement until the condition is met / basically until the button a

Time:03-23

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
import time



def runScript():
    browser = webdriver.Chrome(ChromeDriverManager().install())
    playButton = '//*[@id="game-details-play-button-container"]/button'

    browser.get("https://www.facebook.com")
    browser.find_element_by_xpath('//*[@id="right-navigation-header"]/div[2]/ul/li[2]/a').click()
    browser.find_element_by_xpath('//*[@id="login-username"]').send_keys("123")
    browser.find_element_by_xpath('//*[@id="login-password"]').send_keys("abc")
    browser.find_element_by_xpath('//*[@id="login-button"]').click()

    while True:
        if browser.find_element_by_class_name("btn-full-width btn-common-play-game-lg btn-primary-md btn-min-width"):
            browser.find_element_by_xpath(playButton).click()
            break
        else:
            return False
    time.sleep(4)

How do I make my while loop statement loop through the statement until my if statement goes true? I'm using Selenium by the way.

CodePudding user response:

There are several issues here:

  1. Instead of find_element_by_class_name you can use find_elements_by_class_name. The difference is: if no such element found find_element will throw an exception while find_elements will return a list of web elements. In case there is a match, element exits, it will be non-empty list while non-empty list is interpreted by Python as Boolean True. Otherwise, in case no elements found it will return empty list interpreted as a Boolean False.
  2. Since you are locating that element by several class names you should use XPath or CSS Selector, not by_class_name
  3. Instead of find_element_by_css_selector you should use modern style of find_element(By.CSS_SELECTOR, "value")
    With all these and a correct indentation your code can be something like this:
while True:
    if browser.find_elements(By.CSS_SELECTOR,".btn-full-width.btn-common-play-game-lg.btn-primary-md.btn-min-width"):
        browser.find_element(By.XPATH,playButton).click()
        break
    else:         
        time.sleep(0.5)

You will need this import:

from selenium.webdriver.common.by import By
  • Related