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:
- Instead of
find_element_by_class_name
you can usefind_elements_by_class_name
. The difference is: if no such element foundfind_element
will throw an exception whilefind_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 BooleanTrue
. Otherwise, in case no elements found it will return empty list interpreted as a BooleanFalse
. - Since you are locating that element by several class names you should use XPath or CSS Selector, not
by_class_name
- Instead of
find_element_by_css_selector
you should use modern style offind_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