I'm new to coding and I'm trying to learn webpage automation with Selenium.
So far I have managed to open a webpage, make it click where I want it to click and input any words I want. However, I'm struggling with the if variable.
Basically I want to tell Selenium to click a button that I located by xpath. In turn this button should display a new element on the screen that I can also locate by xpath. However, sometimes when I click this button the new element doesn't display. So how can I tell Selenium that if the element doesn't display it should refresh the page and click until the new element is displayed and only then it can click on the new element?
Code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Firefox()
url = "https://www.compumsa.eu/item/GV-R55XTOC-4GD-Gigabyte-Radeon-RX-5500-XT-4GB-OC-PCIE-9320"
driver.get(url)
driver.maximize_window()
click = driver.find_element_by_xpath('//*[@id="ContentPlaceHolderMain_LBAddItem"]')
click.click()
itempanier = driver.find_element_by_xpath('//*[@id="SpanCaddy"]')
if (itempanier.is_displayed()
try - except
with find_elements
, basically find_elements
will return a list in Selenium-Python
and check for it's size if >0
element will be visible if not, go to else block and reload the page and this will be repeating until it breaks from the while loop.break only on two conditions :
Code:
driver = webdriver.Chrome(driver_path)
driver.maximize_window()
driver.implicitly_wait(30)
wait = WebDriverWait(driver, 30)
driver.get("https://www.compumsa.eu/item/GV-R55XTOC-4GD-Gigabyte-Radeon-RX-5500-XT-4GB-OC-PCIE-9320")
click = wait.until(EC.element_to_be_clickable((By.ID, "ContentPlaceHolderMain_LBAddItem")))
click.click()
while True:
try:
itempanier = driver.find_elements_by_xpath('//*[@id="SpanCaddy"]')
if len(itempanier) > 0:
print('Meaning SpanCaddy web element is visible')
# do some stuff like clicking on it and then break from the loop.
#break
else:
print('Meaning SpanCaddy web element is not visible')
# do some other stuff like reload
driver.refresh()
except:
print('Something went wrong')
pass
break
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.