2

I'm trying to create an loop for searching a xpath in a page until is available.

I'm trying with this:

cart = driver.find_element_by_xpath('//*[@id="add-to-cart-button"]')
if not cart:
    webdriver.ActionChains(driver).send_keys(Keys.F5).perform()
else:    
    driver.find_element_by_xpath('//*[@id="add-to-cart-button"]').click()

But is impossible to define cart because the xpath is not yet available.

How you do it?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Angel91
  • 45
  • 6

1 Answers1

0

Wrap the click() within a try/catch{} block as follows:

while True:
    try:
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='add-to-cart-button']"))).click()
        break
    except TimeoutException:
        driver.ActionChains(driver).send_keys(Keys.F5).perform()
        

Note: You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • @Angel91 Minor bug copy/pasting the xpath. Corrected now. Let me know the status. – undetected Selenium Dec 20 '20 at 15:50
  • @Angel91 That's your logic/implementation and I don't have a visibility to your requirement of using `send_keys(Keys.F5)` to refresh the page. – undetected Selenium Dec 20 '20 at 16:02
  • i'm used driver.get("url") insted F5 for refresh the page, but i'v enother problem, when i use the url, the page doesn't show, only if i click in other page element. – Angel91 Dec 20 '20 at 16:20
  • 1
    @Angel91 Seems to be a completely different issue all together. Can you raise a new question as per your new requirement? Stackoverflow contributors will be happy to help you out. – undetected Selenium Dec 20 '20 at 16:23
  • instead of xpath can i use another command? the name of button is Add to car. I can use?: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Add to car']"))).click() – Angel91 Dec 20 '20 at 17:24
  • 1
    @Angel91 Depends on the markup. We need to see the HTML for a optimized [Locator Strategy](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890) – undetected Selenium Dec 20 '20 at 17:50