How can I make this code execute the if statement properly - python

The below code is supposed to wait click a button after 2 seconds. after two clicks it should wait for 15 seconds before proceeding to click again. However the 15 second wait is not happening. What am I doing wrong?
#click follow
clicked=0
try:
Fclick=driver.find_element_by_xpath('//button[text()="Follow"]')
driver.execute_script("arguments[0].click();", Fclick)
time.sleep(1)
inputElement.send_keys(e)
except Exception:
driver.back()
time.sleep(2)
driver.get("https://www.instagram.com/am_batman33/?hl=en")
clicked +=1
if clicked == 2:
clicked = 0
time.sleep(15)
else:
time.sleep(2)

It seems indentation issue. if else condition falls under except block so until and unless if there is no exception in try block, the code won't execute.
Simple solution would be keep your code with same intend as try except block.
clicked=0
try:
Fclick=driver.find_element_by_xpath('//button[text()="Follow"]')
driver.execute_script("arguments[0].click();", Fclick)
time.sleep(1)
inputElement.send_keys(e)
except Exception:
driver.back()
time.sleep(2)
driver.get("https://www.instagram.com/am_batman33/?hl=en")
clicked +=1
if clicked == 2:
clicked = 0
time.sleep(15)
else:
time.sleep(2)

Related

python exception handling order

I am trying to handle an exception in order,
if the first exeption dosn't work it should run the second one, but in code if the 1st exception dosn't work it stop running
try:
driver.find_element_by_xpath(Newtweet_button).click() #tweet button
sleep(2)
except (ElementClickInterceptedException):
driver.find_element_by_xpath(cross_button).click()
driver.find_element_by_xpath(close_button2).click() #if tweet is repeated
sleep(2)
driver.find_element_by_xpath(Newtweet_button).click()
except (ElementClickInterceptedException):
sleep(2)
driver.find_element_by_xpath(Newtweet_button).click() #tweet button
sleep(2)
you cant except this ElementClickInterceptedException or any exception multiple times in the same try/except block.
you CANT do this:
try:
# stuff
except (ElementClickInterceptedException):
# stuff
except (ElementClickInterceptedException):
# stuff
instead you can use this method:
try:
# stuff
except ElementClickInterceptedException:
try:
# stuff
except ElementClickInterceptedException:
# stuff
(btw, parentheses are redundant in python in such situations, loops condition and conditions)
or this method (infinite loop that tries to find the element):
while True:
try:
driver.find_element_by_xpath(Newtweet_button).click()
# if the above works, then quit the exception block
break
except ElementClickInterceptedException:
# except and try again
pass
# and you can sleep here to slow the process
sleep(2)
honestly, i used this method with while True a lot of times, because its the best when trying to find a webelement that is not loaded yet.
of course, you can put a condition to stop the infinite searching when iterates more than a limit set by you.

Button not clicking and getting no errors with Selenium Python

this buttons are not getting clicked
agree_button = driver.find_element_by_xpath('//*[#id="rightsDeclaration"]')
submit = driver.find_element_by_xpath('//*[#id="submit-work"]')
def upload():
agree_button.click()
time.sleep(1)
submit.click()
upload():
however i noticed that when the function is called, the url gets selected like this:
Url selected when the function is called
i tried locating with the id, the name , the xpath , everything and nothing
the buttons:
and also i notcied that the page scrolls a bit down (and not clicking ofc) and that's it. what's the problem?
full code:
copy_settings_link = "https://www.redbubble.com/portfolio/images/68171273-only-my-dog-understands-me-beagle-dog-owner-gift/duplicate"
def copy_settings():
driver.get(copy_settings_link)
replace_image_button = driver.find_element_by_xpath('//*[#id="select-image-base"]')
time.sleep(1)
replace_image_button.send_keys(Path_list[0])
upload_check = driver.find_element_by_xpath(
'//*[#id="add-new-work"]/div/div[1]/div[1]/div[1]/div') # CHECKING UPLOAD
while True:
if upload_check.is_displayed() == True:
print('Uploading...')
time.sleep(1)
else:
print('Uploading Finished')
time.sleep(1)
break
copy_settings()
def upload():
agree_button.click()
time.sleep(1)
submit.click()
upload()
Problem Fixed Guys:
this
chrome_options.add_argument("user-data-dir=C:\\Users\\Username\\AppData\\Local\\Google\\Chrome\\User Data") # Stay LOGGED IN
can anyone explain please to me how this code works? it let me stay logged in in the site

Selenium Alert Handling Python

So I am using Selenium to simply go to a given list of websites and take a screenshot of them. However I have run into some having alerts and some do not. I am looking to do something along the lines of if alert then this else keep moving.
Here is my current code
from selenium import webdriver
import pandas as pd
import time
path = "C:/Users/dge/Desktop/Database/NewPythonProject/html Grabber/Output/Pics/"
df = pd.DataFrame()
df = df.append(pd.read_csv('crime.csv'), ignore_index=True)
driver = webdriver.Chrome('C:/Users/dge/Desktop/Database/NewPythonProject/html Grabber/chromedriver.exe')
for i in df.index:
print(i)
pic = path + df['site'][i] + '.png'
driver.get('http://' + df['site'][i])
time.sleep(5)
driver.save_screenshot(pic)
I've seen this but just not sure how to add it in the loop
driver.find_element_by_id('').click()
alert = driver.switch_to_alert()
The best way to put this may be to say ignore any errors and continue on through my list of urls.
JavaScript can create alert(), confirm() or prompt()
To press button OK
driver.switch_to.alert.accept() # press OK
To press button CANCEL (which exists only in confirm() and prompt())
driver.switch_to.alert.dismiss() # press CANCEL
To put some text in prompt() before accepting it
prompt = driver.switch_to.alert
prompt.send_keys('foo bar')
prompt.accept()
There is no function to check if alert is displayed
but you can put it in try/except to catch error when there is no alert.
try:
driver.switch_to.alert.accept() # press OK
#driver.switch_to.alert.dismiss() # press CANCEL
except Exception as ex:
print('Exception:', ex)
Minimal working example.
Because I don't know page which displays alert so I use execute_script to display it.
from selenium import webdriver
import time
#driver = webdriver.Firefox()
driver = webdriver.Chrome()
driver.get('http://google.com')
# --- test when there is alert ---
driver.execute_script("console.log('alert: ' + alert('Hello World!'))")
#driver.execute_script("console.log('alert: ' + confirm('Hello World!'))")
#driver.execute_script("console.log('alert: ' + prompt('Hello World!'))")
time.sleep(2)
try:
driver.switch_to.alert.accept() # press OK
#driver.switch_to.alert.dismiss() # press CANCEL
except Exception as ex:
print('Exception:', ex)
# --- test when there is no alert ---
try:
driver.switch_to.alert.accept() # press OK
#driver.switch_to.alert.dismiss() # press CANCEL
except Exception as ex:
print('Exception:', ex)
# ---
driver.save_screenshot('image.png')
driver.close()
BTW: if you want to first try to press CANCEL and when it doesn't work then press OK
try:
driver.switch_to.alert.dismiss() # press CANCEL
except Exception as ex:
print('Exception:', ex)
try:
driver.switch_to.alert.accept() # press OK
except Exception as ex:
print('Exception:', ex)
BTW: different problem can be popup notifications or geolocation alerts
How to click Allow on Show Notifications popup using Selenium Webdriver

Python selenium script to continue running if element is not found

I am dealing with a pop up issue that seems to be random before I click on a button. I want to know if there is any way I can check if the element is displayed and click it, if it is not displayed, i want it to continue running the script. my current script keeps getting an error. when the pop up is displayed, my script runs PERFECT. my error takes place on my script at the
onetouch = self.driver.find_element _by_xpath("").
Here is a picture of my error:
self.driver.get(redirecturl)
self.driver.implicitly_wait(180)
login_frame = self.driver.find_element_by_name('injectedUl')
# switch to frame to access inputs
self.driver.switch_to.frame(login_frame)
# we now have access to the inputs
email = self.driver.find_element_by_id('email')
password = self.driver.find_element_by_id('password')
button = self.driver.find_element_by_id('btnLogin')
# input your email and password below
email.send_keys('')
password.send_keys('')
button.click()
#############
onetouch = self.driver.find_element_by_xpath(".//*[#id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a")
if onetouch.is_displayed():
time.sleep(2)
onetouch.click()
else:
print "onetouch not present....continuing script"
button2 = self.driver.find_element_by_id('confirmButtonTop')
button2.click()
button3 = self.driver.find_element_by_name('dwfrm_payment_paypal')
# if you want to test the program without placing an order, delete the button3.click() below this.........
button3.click
Actually find_element_by_xpath always returns either element or throws exception, So if there is no element by provided locator you can't execute is_displayed(). You should try using find_elements_by_xpath instead and check the length as below :-
onetouch = self.driver.find_elements_by_xpath(".//*[#id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a")
if len(onetouch) > 0:
time.sleep(2)
onetouch[0].click()
else:
print "onetouch not present....continuing script"
-------
Try following:
from selenium.common.exceptions import NoSuchElementException
try:
time.sleep(2)
self.driver.find_element_by_xpath(".//*[#id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a").click()
except NoSuchElementException:
print "onetouch not present....continuing script"

Selenium Webdriver: (python) wait for element to not be present (not working)

I'm learning about the Selenium web drivers and have started using python to test websites. I'm having issues with the wait for element not to be present code, as it seems to be timing out.
This is the code I have so far.
def test_(self):
driver = self.driver
driver.get(self.base_url + "/abc")
driver.find_element_by_id("UserName").clear()
driver.find_element_by_id("UserName").send_keys("username")
driver.find_element_by_id("Password").clear()
driver.find_element_by_id("Password").send_keys("password")
driver.find_element_by_id("loginbutton").click()
for i in range(60):
try:
if not self.is_element_present(By.CSS_SELECTOR, ".blockUI"): break
except: pass
time.sleep(1)
else: self.fail("time out")
driver.find_element_by_xpath(".//*[#id='ChangeTaskGridM']/table/thead/tr/th[1]/a").click()
for i in range(60):
try:
if not self.is_element_present(By.CSS_SELECTOR, ".blockUI"): break
except: pass
time.sleep(1)
else: self.fail("time out")
driver.find_element_by_xpath(".//*[#id='ChangeTaskGridM']/table/thead/tr/th[2]/a").click()
for i in range(60):
try:
if not self.is_element_present(By.CSS_SELECTOR, ".blockUI"): break
except: pass
time.sleep(1)
else: self.fail("time out")
I'm not sure why it's timing out. If I remove the blockUI it will run to fast and I also don't want to put manual breaks in between. Any ideas?
Current code to detect is_element_present
for i in range(60):
try:
if not self.is_element_present(By.CSS_SELECTOR, ".blockUI"): break
except: pass
time.sleep(1)
else: self.fail("time out")
Instead of your code to check presence of that element you should use ExpectedConditions. Please read the doc for waits. the presence_of_element_located() is probably the one of interest to you.
You put sleep in wrong place, i believe this is what you wanted:
for i in range(60):
try:
if not self.is_element_present(By.CSS_SELECTOR, ".blockUI"):
break
else:
time.sleep(1)
except: pass
also in Python else after for will be always performed after successful end of loop, no wonder you get self.fail("time out") every time

Categories