I have a bunch of functions that do x y and z, these functions get executed after an exception has occured. so my problem is that instead of writing the functions one by one i want to create a list of functions and a write a function to iterate through those functions in the list.
If you could show me an example that would be of great help.
here is what i have:
def call_va_funcs(self, stop):
self.disableZüruckVA()
while True:
try:
correct = urllib.request.urlopen("http://192.168.167.12", timeout=10).getcode()
print(correct, "192.168.100.2 is reachable: FAIL")
if correct == 200:
self.enableZüruckVA()
self.exitflag == True
break
except Exception:
print('Preflash')
if self.exitflag == True:
self.enableZüruckVA()
break
self.ping_all_va()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
self.run_rxtx()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
self.call_netzteil()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
As you can see here i am repeating the same process over and over again but with a different function. Can anyone help me figure out how to have a list and then just iterate through the bunch of functions.
Thank you
Let's say you have functionA(), functionB() and functionC().
You could put the names of the functions in a list like this:
f_list = [functionA, functionB, functionC]
You can then call these functions one after another:
while True:
# other code here...
try:
#... other code
except:
# ...other code
for func in f_list:
func()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
you could try smth like this
my_methods = []
my_methods.append('ping_all_va')
my_methods.append('run_rxtx')
my_methods.append('next_func')
for cmd in my_methods:
method = getattr(self, cmd)
method()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
Hi I'm working on an Instagram bot, I want to put this part of the code into a constantly repeating loop.
driver.find_element_by_xpath("/html/body/div[5]/div[1]/div/div/a")\
.click()
pyautogui.click(x=1063,y=748)
sleep(3)
pyautogui.click(x=1154, y=855)
sleep(3)
pyautogui.write("Woaw lookls like amazing.^^")
sleep(3)
pyautogui.press("enter")
sleep(4)
If you want it to loop indefinitely then you can use.
i = 1
while i < 10:
driver.find_element_by_xpath("/html/body/div[5]/div[1]/div/div/a")\
.click()
pyautogui.click(x=1063,y=748)
sleep(3)
pyautogui.click(x=1154, y=855)
sleep(3)
pyautogui.write("Woaw lookls like amazing.^^")
sleep(3)
pyautogui.press("enter")
sleep(4)
Though I would recommend only looping through this a set number of times and then re-running it if you need to.
If he insists on indefinitely then go:
i = False
while i != True:
This will create an infinate loop until
i = True
I have a simple Python/Selenium script that has to wait for 4 checks to happen. Each of these on a separated thread. On the first thread that returns information, the program should continue and the remaining threads killed (if possible).
I have a program that is creating the threads just fine, but I have no idea on how to continue on the first that have executed.
these are my function definitions:
def wait_by(search_type, locator, timeout):
WebDriverWait(driver, timeout).until(EC.presence_of_element_located((search_type, locator)))
def multi_locator_verify_element(xpath_locator, css_locator, name_locator, id_locator, timeout):
element = ""
if xpath_locator != "":
tx = Thread(target=wait_by, args=(By.XPATH, xpath_locator, timeout))
tx.start()
if css_locator != "":
tc = Thread(target=wait_by, args=(By.CSS, css_locator, timeout))
tc.start()
if name_locator != "":
tn = Thread(target=wait_by, args=(By.NAME, name_locator, timeout))
tn.start()
if id_locator != "":
ti = Thread(target=wait_by, args=(By.ID, id_locator, timeout))
ti.start()
The multi_locator_verify_element function should finish after the first thread has been able to retrive the right element.
Could someone please help me with that?
Regards,
I'm new to Python and have been googling for a couple of days and read all I can find on this forum. Might be that I don't understand it all but I haven't found a solution to my problem yet. Ask for forgiveness already if there's an answer already to my problem, then I haven't understood it.
I want to make a Pause function for my program Tennismatch. The program will when it's being run print the score of a tennis match like this: "15-0, 15-15 etc ongoing till the match ends. It will print the score line by line.
I want the user to be able to pause after x number of balls, games, etc. So I don't know when the user wants to pause and after the user has paused I want the user to be able to resume the tennismatch where it was.
Have seen the time.sleep() but as I have understood it you must know when you want to pause to use this and it also ain't an indefinetie pause like I want. With input() it's the same.
Am going to make a GUI later on when the code is finished. Happy for anything that leads me to solving my problem.
I use Windows and Python 3.42 and run the program in Shell.
A piece of the code (haven't written it all yet, it's more of a general situation when something is being printed line after line for some time and want to be able do pause in the CIL:
#self.__points = [0,0]
def playGame(self):
if self.server == True: #self.server is either True or False when someone calls playGame()
server = self.player_1.get_win_serve() #self.player_1 = an object of a class Player():
else:
server = self.player_2.get_win_serve() #get_win_serve() method returns the probability to win his serv (1-0)
while (0 < self.__points[0] - self.__points[1] >= 2 or 0 < self.__points[1] - self.__points[0] >= 2) and (self.__points[1] >= 4 or self.__points[0] >= 4):
x = random.uniform(0,1)
if x > 0 and x < server:
self.__points[0] += 1
else:
self.__points[1] += 1
# print('The score, by calling a score() function that I haven't written yet')
For dealing with events in main loop you need to make a separated thread which capture input or any other event.
import sys
from sys import stdin
from time import sleep
from threading import Thread
from Queue import Queue, Empty
def do_something():
sleep(1)
print 42
def enqueue_output(queue):
while True:
# reading line from stdin and pushing to shared queue
input = stdin.readline()
print "got input ", input
queue.put(input)
queue = Queue()
t = Thread(target=enqueue_output, args=(queue,))
t.daemon = True
t.start()
pause = False
try:
while True:
try:
command = queue.get_nowait().strip()
print 'got from queue ', command
except Empty:
print "queue is empty"
command = None
if command:
if command == 'p':
pause = True
if command == 'u':
pause = False
if not pause:
print pause
do_something()
except KeyboardInterrupt:
sys.exit(0)
I came up with the following.
while True:
try:
## Keep doing something here
## your regular code
print '.',
except KeyboardInterrupt:
## write or call pause function which could be time.sleep()
print '\nPausing... (Hit ENTER to continue, type quit to exit.)'
try:
response = raw_input()
if response.lower() == 'quit':
break
print 'Quitting...'
except KeyboardInterrupt:
print 'Resuming...'
continue
The Event loop might as well be the code I wrote with.
I don't see any user input so I assume that x emulates it. To pause the game if x < 0.1 and to unpause(/resume) it if x > 0.9, you could:
while your_condition(self.__points):
x = random.random()
if x < 0.1: # pause
self.pause()
elif x > 0.9: # resume
self.resume()
if self.is_paused:
continue # do nothing else only wait for input (`x`)
# assume your_condition() has no side-effects
# here's what the resumed version does:
print("...")
# change self.__points, etc
where pause(), resume(), is_paused() methods could be implemented as:
def __init__(self):
self.is_paused = False
def pause(self):
self.is_paused = True
def resume(self):
self.is_paused = False
as you can see the implementation is very simple.
I am trying to submit an input(type= button).But I am unable to update the value.
Any help is appreciated.
I have attached the testcase below for your reference.
search for CLICK FAILS HERE
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re,datetime,os,sys
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
def is_element_present(inst,selector,value):
try:
inst.find_element(by=selector, value=value)
return True
except:
return False
class Testing(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(5)
self.base_url = "http://new.ossmoketest.appspot.com/"
self.verificationErrors = []
def test_ing(self):
try:
driver = self.driver
driver.get(self.base_url + "/Apab4b39d4_09d7_11e1_8df9_139372201eeb/1/signin?forward=/%3F")
now = datetime.datetime.now()
start = time.clock()
for i in range(5000000):
try:
if is_element_present(driver,By.ID,"userid"): break
except: pass
else: self.fail("time out")
end = time.clock()
diff = end - start
print diff
driver.find_element_by_id("userid").clear()
driver.find_element_by_id("userid").send_keys("senthil.arumugam#orangescape.com")
driver.find_element_by_xpath("//input[#src='/static/images/signup.png']").click()
print 'finished'
start = time.clock()
for i in range(5000000):
try:
if is_element_present(driver,By.LINK_TEXT,"Logout"): break
except: pass
else: self.fail("time out")
end = time.clock()
diff = end - start
print diff
time.sleep(5)
start = time.clock()
name = "smoketest"+ str(now.minute) +str(now.second)
for i in range(5000000):
try:
if is_element_present(driver,By.LINK_TEXT,"PurchaseOrder"): break
except: pass
else: self.fail("time out")
end = time.clock()
diff = end - start
driver.find_element_by_link_text('PurchaseOrder').click()
name = "smoketest"+ str(now.minute) +str(now.second)
start = time.clock()
for i in range(5000000):
try:
if is_element_present(driver,By.ID,"Customer_Name"): break
except: pass
else: self.fail("time out")
end = time.clock()
diff = end - start
newproduct = "rexona"+ str(now.minute) +str(now.second)
newprice = str(now.minute) +str(now.second)
newprice = float(newprice)
print newprice
driver.find_element_by_xpath("//input[starts-with(#id,'New_Product')]").send_keys(newproduct)
driver.find_element_by_xpath("//input[starts-with(#id,'Price')]").clear()
time.sleep(3)
driver.find_element_by_xpath("//input[starts-with(#id,'Price')]").send_keys(Keys.CONTROL+'a'+Keys.NULL, str(newprice))
Mouse_cntrl = ActionChains(driver)
Mouse_cntrl.release(driver.find_element_by_xpath("//input[starts-with(#id,'Price')]"))
value = newprice
print value
time.sleep(2)
print 'start'
print driver.find_element_by_xpath("//input[starts-with(#id,'NewItem_NewItem')]").get_attribute('data-id')
# ------------------------CLICK FAILS HERE ------------------------------
# driver.find_element_by_xpath("//input[starts-with(#id,'NewItem_NewItem')]").click()
# driver.find_element_by_xpath("//input[starts-with(#id,'NewItem_NewItem')]").submit()
driver.find_element_by_xpath("//input[starts-with(#id,'NewItem_NewItem')]").send_keys(keys.ENTER)
# Mouse_cntrl.double_click(driver.find_element_by_xpath("//input[starts-with(#id,'NewItem_NewItem')]"))
for i in range(10):
try:
print driver.switch_to_alert().text
if driver.switch_to_alert():
driver.switch_to_alert().accept()
break
except: pass
time.sleep(1)
else:
print "alert not found"
print 'finished -- '
time.sleep(8)
driver.find_element_by_xpath("//input[starts-with(#id,'Product')]").click()
arg = newproduct
print 'end'
for i in range(60):
try:
if is_element_present(driver,By.LINK_TEXT,arg): break
except: pass
time.sleep(1)
else: self.fail("time out")
# sel.mouse_over("//html/body/ul/li/a[.=\""+arg+"\"]")
driver.find_element_by_link_text(arg).click()
start = time.clock()
time.sleep(25)
for i in range(1000000):
try:
if newprice == float(driver.find_element_by_id('Unit_Price').text):
end = time.clock()
diff = end - start
log.log(module='Smoke',testcase='Action New', result='Pass',time_taken= diff)
break
except: pass
else:
log.log(module='Smoke',testcase='Action New', result='Fail')
self.fail('New Failure')
log.log(module='Smoke',testcase='On Submit', result='Pass',time_taken= diff)
driver.find_element_by_id('Quantity').send_keys(Keys.CONTROL+'a'+Keys.NULL,"1")
time.sleep(5)
start = time.clock()
for i in range(1000000):
try:
if value == float(driver.find_element_by_id('Unit_Price').text):
end = time.clock()
diff = end - start
log.log(module='Smoke',testcase='Multiply', result='Pass',time_taken= diff)
break
except: pass
else: self.fail("time out")
for i in range(1000000):
try:
if value == float(driver.find_element_by_id('Amount').text):
end = time.clock()
diff = end - start
log.log(module='Smoke',testcase='DSUM with Parent', result='Pass',time_taken= diff)
break
except: pass
else:
end = time.clock()
diff = end - start
log.log(module='Smoke',testcase='DSUM with Parent', result='Fail',time_taken= diff)
self.fail("time out")
except:
self.driver.quit()
e = sys.exc_info()[1]
print str(e)
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
It has been a showstopper for my work. Any help is appreciated.Thanks
You could try substituting .click() with .send_keys("\n"), which is equivalent to "Pressing enter while focusing on an element".
So this:
driver.find_element_by_link_text('PurchaseOrder').click()
would become this:
driver.find_element_by_link_text('PurchaseOrder').send_keys("\n")
In case this is still a recurring problem for anyone else, if you have confirmed your code is correct (you've reviewed it for errors etc.) and you still find the find_element_by_...('text').click() function not working properly it is often due to your code continuing to run before the JavaScript can update the page.
A simple solution is to import time then insert the below code immediately after any click() methods:
time.sleep(2)
The duration of the sleep timer can be whatever you choose. In my case I used 2 seconds. Hopefully that helps.
I had this problem as well. Sometimes, for whatever reason webdriver didn't click the button. It was able to find the button (it didn't throw a NoSuchElementException and a WebDriverWait didn't help).
The problem with clicking the button twice was that if the first click succeed, the second one would fail (or click the submit button on the next page if it found a match!). My first attempt was to put the second click in a try/except block - this is how I found out about it clicking submit on the next page. XD And it also really slowed down my test when it couldn't find the second button.
I found some good insights at Selenium 2.0b3 IE WebDriver, Click not firing. Basically, I click on a parent element first, which seemingly does nothing. Then I click on the submit button.
If the element you click() is an url. I found that taking the href properties and using driver.get(elem.get_attribute('href')) being the cleanest.
I would try other element finders like className, cssSelector or something. xPath sometimes doesnt provide errors if the element isn't found.
So first start by finding out if the element is really found by webdriver.
You can also try to click or use the other commands two times in a row. This already solved some of such issues.
I had the same issue where a two-part drop down menu selection would not generate what it's supposed to generate with proper selections. It worked when I did imported time and use time.sleep(2) between the two "click"s. (For reference I used find_element_by_xpath to find an modify the options.)
I ran into the above issue where the same .click() is working in all browsers(IE, Chrome and Firefox) but not working for Safari. So I tried all the possible solutions from this post and none of them worked and it doesn't even throw error.
I tried below by substituting .click() with .submit(), which is an equivalent method and it worked not only for Safari but also for all other browsers.
So this:
driver.find_element_by_id('login_btn').click()
Replaced as:
driver.find_element_by_id('login_btn').submit()
If above fails to work on other browsers due to any reason keep .submit() in try and except. If it fails .click() will be triggered and executed.
Hope this helps if none of the other solutions works.
For those, click() doesn't work, use submit() if that button element(clickable element) is in a form element. Basically, in order to submit a form, we need to use submit(), click() will not work in some cases.
I foolishly did elem.click with the parentheses: elem.click().