I am trying to test a web portal using Selenium and Python. The problem is, I am unable to get around an error, in other words, I am unable to catch the alert.
Scenario:
Search for a user, if the user is not found, the website throws an error. I have a list that contains valid and invalid users to perform the search upon. When the search is successful, there are a few links I need to click to get to the user. If the user is not found, the links won't be displayed and an error is displayed instead. The problem is when I search for an invalid user, the code is looking for the links that are displayed when the a valid user is displayed.
Code:
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.alert import Alert
from selenium.common.exceptions import NoAlertPresentException
import time
browser = webdriver.Chrome() # type: WebDriver is Chrome
browser.get("https:URL")
if option == 'number':
nums = ['111', '123', '456']
searchbox = browser.find_element_by_id("searchPattern")
noUser = browser.find_element_by_xpath('//*[@id="includeError"]/div')
try:
for num in nums:
searchbox.send_keys(num)
browser.find_element_by_xpath('//[@id="User"]/input[2]').click()
time.sleep(4)
user_links = ['photos', 'message', 'mails']
for url in user_links:
if url in user_links:
browser.find_element_by_link_text(url).click()
time.sleep(4)
elif url not in user_links:
print "No users found"
browser.switch_to_window(browser.window_handles[0])
time.sleep(5)
browser.find_element_by_id('searchPattern').clear()
except noUser:
print "no users"
-
The alert is not a pop up but just a text alert on the page " User not found "Dev Bin– Dev Bin2018年08月10日 21:08:41 +00:00Commented Aug 10, 2018 at 21:08
-
If a user is found, the user details are displayed with the links for that user Photos Message mailsDev Bin– Dev Bin2018年08月10日 21:09:07 +00:00Commented Aug 10, 2018 at 21:09
-
please post console errorsameer joshi– sameer joshi2018年08月14日 10:33:04 +00:00Commented Aug 14, 2018 at 10:33
-
I was able to fix the code by looking up the error text in the html source.Dev Bin– Dev Bin2018年08月16日 18:38:36 +00:00Commented Aug 16, 2018 at 18:38
1 Answer 1
The below code resolved my issue:
error = " No users found"
if error in page_source:
print " error to console"
else:
// my code user defined action
The above code ignores the error if the error was there and continued with the search function.