How do I optimize my code with try statement? - python

I have a problem that it takes a long time to execute the code that follows the try. It can be up to 10 seconds. Can you think of any optimization?
try:
error_message = WebDriverWait(self.driver, timeout=0).until(EC.visibility_of_element_located(
(By.XPATH, "/html/body/div[1]/div[2]/div/div/div[1]/span[2]")))
assert error_message.text == "Invalid username or password."
print("3")
print("Invalid username or password.")
self.driver.find_element_by_id("username").clear()
except TimeoutException:
print(time.time(), "3")

I put the part of code for initializing the web drive. Maybe here is something wrong what do it wait in try long time.
def setUp(self):
p_test = Logintest()
self.driver = webdriver.Firefox()
self.driver.get("https://localhost/spcssd")
print("TC_S_F.IA.AD001_tEST")
delay = 20 # seconds
# assert "Log in to spcssd" in self.driver.title
try:
element_present = WebDriverWait(self.driver, delay).until(EC.presence_of_element_located((By.ID, "kc-info")))
print("Page is ready!")
except TimeoutException:
print("Loading took too much time!")

Related

How to while loop exception in Python

Someone said to me that I need to convert my code below to while or for loops.
driver.switch_to_window(driver.window_handles[1])
def edit_button(max_sec=10):
try:
WebDriverWait(driver, 1).until(EC.element_to_be_clickable(
(By.XPATH, "//button[contains(text(),'Edit')]")))
print("detected")
except:
driver.refresh()
max_sec -= 1
print(max_sec)
if max_sec == 0:
driver.close()
driver.switch_to_window(driver.window_handles[0])
print("not detected")
edit_button(max_sec)
edit_button()
The code above means that if edit button is not detected, then refresh until it appears for maximum of 10 seconds.
I tried to convert it to while loops, but it shows EXCEPTION ERROR. because this is not detected:
WebDriverWait(driver, 1).until(EC.element_to_be_clickable(
(By.XPATH, "//button[contains(text(),'Edit')]")))
Here is my while loop:
max_sec = 10
while not WebDriverWait(driver, 1).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(),'Edit')]"))):
driver.refresh()
max_sec -= 1
print(max_sec)
if max_sec == 0:
driver.close()
driver.switch_to_window(driver.window_handles[0])
sys.exit()
print("success")
How to make something like this:
while element is exception:
Thanks sorry I am new to Python.
You could change loop condition and catch exception normally with try/except inside loop.
Here is the example:
seconds_left = 10
while seconds_left != 0:
try:
WebDriverWait(driver, 1).until(
EC.element_to_be_clickable(
(By.XPATH, "//button[contains(text(),'Edit')]"),
),
)
break
except:
seconds_left -= 1
driver.refresh()
if seconds_left == 0:
driver.close()
driver.switch_to_window(driver.window_handles[0])
sys.exit()
print("success")

Python- How that should be loop which repeat the code?

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

return to first function() at the end of last function()

If you scroll to the bottom of below; I am trying to return to the first function at the end of my last function using process_records()
. My attempt returns Undefined variable 'process_records'pylint(undefined-variable)
def process_records(self, records, map_data, completed=None, errors=None):
"""Code to execute after webdriver initialization."""
series_not_null = False
try:
num_attempt = 0
for record in records.itertuples(): # not working
print(record)
series_not_null = True
self.navigate_to_search(num_attempt)
self.navigate_to_member(mrn)
self.navigate_to_assessment()
self.add_assessment(record, map_data)
self.driver.switch_to.parent_frame() # not working
sleep(.5)
except Exception as exc:
if series_not_null:
errors = self.process_series_error(exc)
return completed, errors
def navigate_to_search(self, num_attempt):
"""Uses webdriver to navigate to Search tab and select Member Status=All"""
if num_attempt == 0:
page_change_until(self.driver, By.XPATH, './/*[text()="Search"]')
wait_ready_state(self.driver)
else:
self.driver.switch_to.parent_frame()
elem = wait_until(self.driver, By.XPATH, './/*[text()="Search"]')
is_disp_n = 0
while True:
if elem.is_displayed():
break
else:
self.driver.switch_to.parent_frame()
is_disp_n += 1
sleep(1)
if is_disp_n == 20:
raise Exception('Could not find Search tab after 20 tries.')
num_attempt += 1
radio_locator = (By.XPATH, './/*[#type="RADIO"][#value="All"]')
while True:
break_while_timer = datetime.now()
if datetime.now() - break_while_timer > timedelta(seconds=20):
break_while = True
break
try:
if wait_until(self.driver, *radio_locator).is_selected():
pass
else:
wait_until(self.driver, *radio_locator).click()
break
except Exception:
sleep(1)
def navigate_to_member(self, mrn):
"""Finds member"""
wait_until(self.driver, By.XPATH, './/*[#name="MemberIdItem_1"]').clear()
wait_until(self.driver, By.XPATH, './/*[#name="MemberIdItem_1"]').send_keys(f'{mrn}'+Keys.ENTER)
page_change_until(self.driver, By.XPATH, f'.//*[text()="{mrn}"]')
wait_ready_state(self.driver)
def navigate_to_assessment(self):
"""Navigates to the appropriate contact log"""
self.driver.find_element_by_css_selector("div[eventproxy^='memberAssessment']").click() #clicks assessment icon
element = self.driver.find_element_by_xpath(f"//div[contains(text(), '{self.assessment_type}')]")
actions = ActionChains(self.driver)
actions.move_to_element(element).perform()
self.driver.find_element_by_xpath(f"//div[contains(text(), '{self.assessment_type}')]").click()
self.driver.find_element_by_css_selector("div[eventproxy^='createSelectedAssessmentsButton']").click()
def add_assessment(self, record, map_data):
"""Create contact log"""
qna_frame = self.driver.find_element_by_css_selector("iframe[id^='iccc']")
self.driver.switch_to.frame(qna_frame)
pages = self.driver.find_element_by_css_selector("ul[class='nav nav-pills nav-stacked qna-tabs']")
pages = pages.find_elements_by_css_selector("a")
for page in pages:
page.click()
# for record in records.itertuples(): #attempt
questions = self.driver.find_elements_by_css_selector("fieldset")
questions = [question for question in questions if question.text not in ("", " ", None)]
for question in questions[1:]:
q_text = question.find_element_by_css_selector("span[class='question-text ng-binding']").text
questionType = map_data.loc[map_data['question_text'] == q_text, 'question_type'].item()
answer = map_data.loc[map_data['question_text'] == q_text, 'map'].item()
answer = getattr(record, answer)
if answer not in ("", " ", "NaT", "NaN", None):
if questionType == 'checks':
self.choose_checks(question, answer)
else:
try:
if questionType == 'text':
self.driver.implicitly_wait(0)
(question.find_element_by_css_selector("textarea").send_keys(str(answer))
if
question.find_elements_by_css_selector("textarea")
else
question.find_element_by_css_selector("input").send_keys(answer))
self.driver.implicitly_wait(15)
elif questionType == 'date':
try:
answer = answer.strftime('%m/%d/%Y')
question.find_element_by_css_selector("input").send_keys(answer)
# page.click()
except Exception as e:
raise Errors.RequiredDataError('Issues with Assessment Date -- {}'.format(e))
elif questionType == 'radio':
question.find_element_by_css_selector("input[value='{}']".format(answer)).click()
except:
continue
else:
pass
self.driver.find_element_by_css_selector("#publishButton").click()
sleep(3)
WebDriverWait(self.driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".btn.btn-mini.btn-primary"))).click()
process_records()
I have also tried:
self.process_records()
This whole code-block seems to be inside a class. So you should be using self.process_records() to call the function.
The process_records method expects a few positional arguments (apart from self) - you'll probably need to pass those to the function too.

python selenium log number of times page refreshes

I want to know if there is any way to log the number of times my page has refreshed in command prompt when running.
want it to tell me the number of times it has refreshed. Refresh is located between while true: and continue. thanks
driver = webdriver.Chrome(chrome_path)
driver.get(link)
while True:
size = driver.find_elements_by_xpath(".//*[#id='atg_store_picker']/div/div[2]/div[1]/div[1]/span[2]/a[4]")
if len(size) <= 0:
time.sleep(0.5)
print "PAGE NOT LIVE"
driver.refresh()
continue
else:`enter code here`
print 'LIVE!!!!'
break
the answer to my question was very simple...
driver = webdriver.Chrome(chrome_path)
driver.get(link)
count = 0
while True:
size = driver.find_elements_by_xpath(".//*[#id='atg_store_picker']/div/div[2]/div[1]/div[1]/span[2]/a[4]")
if len(size) <= 0:
count +=1
print 'Refresh Count:', count
time.sleep(2)
driver.refresh()
continue
else:
print 'LIVE!!!!'
break

Using Python bindings, Selenium WebDriver click() is not working sometimes.

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().

Categories