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"
Related
I have a SeleniumBase code like this
from seleniumbase import SB
from func_timeout import func_set_timeout, FunctionTimedOut
def checkbox():
print('- click checkbox')
checkbox = 'span#recaptcha-anchor'
try:
sb.wait_for_element(checkbox)
sb.click(checkbox)
sb.sleep(4)
except FunctionTimedOut as e:
print('- 👀 checkbox:', e)
When I call checkbox() it gives error and the browser crashes quickly without clicking the checkbox
I tried replacing
checkbox = 'id#recaptcha-anchor-label'
checkbox = 'id#rc-anchor-center-item'
but it didn't work
You might want to try avoiding the captcha altogether by running SeleniumBase in undetected-chromedriver mode (set uc=True, or run with --uc):
from seleniumbase import SB
with SB(uc=True) as sb:
sb.open("https://nowsecure.nl/#relax")
try:
sb.assert_text("OH YEAH, you passed!", "h1", timeout=7)
sb.post_message("Selenium wasn't detected!", duration=2)
print("\n Success! Website did not detect Selenium! ")
except Exception:
print("\n Sorry! Selenium was detected!")
If you still need to go through the captcha, then make sure that if you need to click something in an iframe, that you switch to the iframe first, such as with sb.switch_to_frame("iframe").
Also, the sb.click(selector) method will automatically wait for the element, which means that calling sb.wait_for_element(selector) before that is unnecessary.
def check_follow_back(page,name_my_page):
driver.get(f'https://www.instagram.com/{page}/')
time.sleep(2.5)
try :
driver.find_element_by_class_name('_7UhW9 vy6Bb MMzan KV-D4 uL8Hv T0kll ').click()
except:
try:
driver.find_element_by_class_name('div._7UhW9 vy6Bb MMzan KV-D4 uL8Hv T0kll ').click()
except:
driver.find_element_by_xpath('//div[#class="_7UhW9 vy6Bb MMzan KV-D4 uL8Hv T0kll "]').click()
print('click')
Here I tried to click on the part of Instagram that shows my following and after run Is shown print on terminal and it did not click on the part I want
The code doesn't have problems, but you never call your function.
Try to add:
func = check_follow_back(page,name_my_page)
with proper parameters
I wrote this script with Python tkinter and Selenium.
I create a button, when we click on it, 2 functions have to be executed. But I don't know why, it doesn't work well, only the first one: login() is executed and the second one: kalk() will not be executed.
If I put all the lines of the 2 functions in only one function, it works until the end without any problem.
Why does the below code not work ?
Here is the code (only a part of the program):
def login():
boutoncount.config(state='disabled')
browser = webdriver.Chrome(executable_path=r"C:\Users\Bat02\Desktop\Python\Selenium Test\chromedriver.exe")
browser.get('url')
time.sleep(10)
login= browser.find_element_by_id("UserID")
pwd = browser.find_element_by_id("Password")
confirm= browser.find_element_by_id("LogIn")
login.send_keys(loginentry.get())
pwd.send_keys(pwdentry.get())
time.sleep(3)
confirm.click()
def kalk():
time.sleep(10)
kalknum= browser.find_element_by_id("txt_Kalk")
eigkalkuncheck=browser.find_element_by_id("chk_Kalk")
eigkalkuncheck.click()
kalknum.send_keys(user_entries[0].get())
boutoncount=Button(fenetre,text="count",width=800,height=1,bg="white", font="bold",bd=5, command=lambda:[login(),kalk()])
boutoncount.pack(side=BOTTOM)
Thank you !
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
I'm trying to assert that the currently needed browser window is opened via selenium.
My approach is to compare titles of the windows to each other, and if title doesn't match - switch to the next window and repeat procedure. But right now check of the last window (which is correct) doesn't happen.
Method for collecting all opened browser windows:
def collect_windows(self):
windows = []
try:
for handle in self.driver.window_handles:
windows.append(handle)
return windows
except:
self.log.error(format_exc())
Method that runs through the list and checks titles of the windows:
def switch_window(self, window_title=''):
windows_list = self.collect_windows()
try:
for window in windows_list:
title = self.driver.title
if window_title not in title:
self.driver.switch_to.window(window)
self.log.info(f"Switched to window: {window_title}")
except:
self.log.error(format_exc())
Instead of comparing titles compare the window handles
def get_current_window_handle(self):
return self.driver.current_window_handle
def switch_window(self, current_handle):
for handle in self.driver.window_handles:
if handle != current_handle:
self.driver.switch_to.window(handle)
self.log.info(f"Switched to window: {self.driver.title}")
return
current_window_handle = get_current_window_handle()
# open new window
switch_window(current_window_handle)