Home > Net >  Python try except function with time-out limit
Python try except function with time-out limit

Time:02-16

I am searching within a PowerBI dashboard with Selenium a certain pop-up window to insert a search term. I can only do this in stable way by creating a function which looks for all input fields and then try to send the term within a try-except-clause which takes very long.

Hence I am wondering if it is possible to insert a command how long to wait till an exception occurs.

Here is my code

fields_searchheader = browser.find_elements_by_css_selector(".searchHeader.show > .searchInput")
for i in fields_searchheader:
    try:
        i.clear()
        i.send_keys("hallo)
        # wait function till exception if no feedback
    except Exception:
        print("d")

Would be great to get an idea. Thanks!

CodePudding user response:

I would recommend to you to use - Expected Conditions

And also to make it stable - tune it by using polling.

CodePudding user response:

Something like this?

it will wait up to..not for the number of seconds..

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common import exceptions
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys









def InputByCSS(NameOfObject, WhatToSend):
    try:
        item = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, NameOfObject)))
        item.click()
        item.send_keys(Keys.CONTROL, 'a')
        item.send_keys(WhatToSend)
    except TimeoutException as e:
        print("InputByXPATH Error: Couldn't input by XPATH on: "   str(NameOfObject))
        pass

fields_searchheader = browser.find_elements_by_css_selector(".searchHeader.show > .searchInput")
for i in fields_searchheader:
    try:
        InputByCSS(i,'hallo')
    except Exception:
        print("d")
  • Related