How to close browser pop-ups using Selenium in python? - python

I'm trying to automate a download using Python and Selenium. In the start page, a pop-up appears on the page:
How can I close it using Selenium?
I tried the following ways but all failed:
>>> alert = browser.switch_to_alert()
>>> alert.accept()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/common/alert.py", line 80, in accept
self.driver.execute(Command.ACCEPT_ALERT)
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
self.error_handler.check_response(response)
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response
raise exception_class(message, screen, stacktrace)
NoAlertPresentException: Message: no alert open
(Session info: chrome=59.0.3071.115)
(Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-57-generic x86_64)
>>> alert.dismiss()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/common/alert.py", line 71, in dismiss
self.driver.execute(Command.DISMISS_ALERT)
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
self.error_handler.check_response(response)
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response
raise exception_class(message, screen, stacktrace)
NoAlertPresentException: Message: no alert open
(Session info: chrome=59.0.3071.115)
(Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-57-generic x86_64)
>>>alert = browser.switch_to_window('Open xdg-open?')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 531, in switch_to_window
self._switch_to.window(window_name)
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/switch_to.py", line 92, in window
self._driver.execute(Command.SWITCH_TO_WINDOW, data)
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
self.error_handler.check_response(response)
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response
raise exception_class(message, screen, stacktrace)
NoSuchWindowException: Message: no such window
(Session info: chrome=59.0.3071.115)
(Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-57-generic x86_64)
>>> alert = browser.switch_to.window("Open xdg-open?")
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/switch_to.py", line 92, in window
self._driver.execute(Command.SWITCH_TO_WINDOW, data)
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
self.error_handler.check_response(response)
File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response
raise exception_class(message, screen, stacktrace)
NoSuchWindowException: Message: no such window
(Session info: chrome=59.0.3071.115)
(Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-57-generic x86_64)

The problem you face is, that the popup is not part of the DOM and thus can neither be handled by selenium by sending keystrokes nor waiting nor clicking somewhere. The popup is a browser native popup and thus can only be handled by the browser itself, usually by user interaction.
To prevent the interaction you can define beforehand which action the browser should take in the circumstance that a link uses a certain protocol. Think hrefs with telephone links:
<p>Book now, call 01234 567 890</p>
The user preferences have to be changed on/before browser start. The handling of protocol schemes can be predefined in the user preferences. In my case I wanted to deny handling of the scheme tel://.
To change the user preferences on startup extend the browsers capabilities and specify user preferences under prefs of the chromeOptions:
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option( "prefs", {'protocol_handler.excluded_schemes.tel': false})
driver = webdriver.Chrome(chrome_options=chrome_options)
In your case it is probably a googlePlay link. So instead of tel: false use the protocol in question instead of tel.

You should first try this in order to see if it's an error related to waits.
i.e : if your browser doesn't have enough time to find the alert dialog before making actions. You can learn more about explicit waits. here
you will also need expected_conditions package and try the following:
# add these imports
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
#try to find the alert and do stuff
try:
#wait for the alert to show up
WebDriverWait(browser, 3).until(EC.alert_is_present(),
'Timed out waiting for PA creation ' +
'confirmation popup to appear.')
#if it does
alert = browser.switch_to.alert()
alert.accept()
print "alert accepted"
except TimeoutException:
print "no alert"
Note that i precised to wait for 3 seconds, you can change it to whatever you like.
if this solution doesn't work, you should try a trick to explicitly select the dialog popup by name or text etc..

Related

Why I am having an error on send_keys using selenium python

I'm trying to make a script that logs me into my account automatically and I'm stuck at send_keys.
I have the latest version of selenium, I'm using python 2.7.18.
here is my script:
from selenium import webdriver
from time import sleep
username = 'username'
driver = webdriver.Chrome()
driver.get('https://www.instagram.com/')
sleep(4)
email = '//*[#id="react-root"]/section/main/article/div[2]/div[1]/div/form/div[2]/div/label/input'
login = driver.find_element_by_xpath(email).send_keys(username)
The error is:
Traceback (most recent call last):
File "C:\Users\Jameel\Desktop\selenium1.py", line 14, in <module>
login = driver.find_element_by_xpath(email).send_keys(username)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py",
line 479, in send_keys
'value': keys_to_typing(value)})
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py",
line 633, in _execute
return self._parent.execute(command, params)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py",
line 321, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py",
line 242, in check_response
raise exception_class(message, screen, stacktrace) WebDriverException: Message: unknown error: call function result
missing 'value' (Session info: chrome=83.0.4103.61) (Driver info:
chromedriver=2.31.488763
(092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT
10.0.17763 x86_64)
I know the script isn't complete.
Generally different sites follow different design approaches, which doesn't allow normal script flow & needs additional steps to be added.
In you case, the default CSS style blocks your input. So, first click on that element( Which makes it as focused) then send your keys.
Element Attribute differences below,
Before click action
After click action

Selenium doesnt fetch url (3 lines of python)

Using chrome 76.0.3809.132 with chromedriver 76.0.3809.126 the testing browser opens but throws a traceback on the driver.get. It isn't able to fetch the page.
Tried couple of arguments, and tried looking for an older version of Chrome with an older chrome driver, which seems impossible.
from selenium import webdriver
driver = webdriver.Chrome("C:/chromedriver/chromedriver.exe")
driver.get("www.google.com")
Output:
DevTools listening on ws://127.0.0.1:57577/devtools/browser/7494ca24-60fb-4b14-9aed-4f25232b94bd
Traceback (most recent call last):
File "slidingwindow.py", line 5, in <module>
driver.get("www.google.com")
File "C:\projects\python\harvester\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 333, in get
self.execute(Command.GET, {'url': url})
File "C:\projects\python\harvester\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\projects\python\harvester\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument (Session info: chrome=76.0.3809.132)
Try to insert https://:
from selenium import webdriver
driver = webdriver.Chrome(executable_path="chromedriver.exe")
driver.get("https://www.google.com")

Slate Element Reference Exception when handling frames

from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'C:\Users\satyanarayana\Downloads\chromedriver_win32\chromedriver.exe')
driver.get("https://www.olx.in/")
frames_tag = driver.find_elements_by_tag_name("iframe")
print(len(frames_tag))
for i in range(0,len(frames_tag)):
driver.switch_to.frame(frames_tag[i])
driver.quit()
I am getting the following exception. Can someone help me figure out what's wrong with the code.
Traceback (most recent call last):
File "C:/Users/satyanarayana/PycharmProjects/untitled1/Ad.py", line 11, in <module>
driver.switch_to.frame(frames_tag[i])
File "C:\Users\satyanarayana\PycharmProjects\untitled1\venv\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 89, in frame
self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference})
File "C:\Users\satyanarayana\PycharmProjects\untitled1\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\satyanarayana\PycharmProjects\untitled1\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=70.0.3538.77)
(Driver info: chromedriver=2.43.600210 (68dcf5eebde37173d4027fa8635e332711d2874a),platform=Windows NT 10.0.17134 x86_64)
When you switch to <iframe> the driver context changes to the <iframe> and can recognize only the elements inside it. You need to switch out of the <iframe> after finishing with it
for i in range(0,len(frames_tag)):
driver.switch_to.frame(frames_tag[i])
driver.switch_to.default_content()

Selenium chromedriver 2.25 TimeoutException cannot determine loading status

I am using python3 on mac os and I have updated chrome, chromedriver and selenium to the latest version. I am getting a TimeoutException, the browser opens correctly but it freezes.
>>> from selenium import webdriver
>>> driver = webdriver.Chrome()
# opens browser with blank page
>>> driver.get('http://example.com')
# gets first page OK and then driver literally flashes once
>>> driver.get('http://stackoverflow.com')
>>>
# Cursor loading forever... until TimeoutException
This error is thrown:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 248, in get
self.execute(Command.GET, {'url': url})
File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: timeout: cannot determine loading status
from timeout: Timed out receiving message from renderer: -0.003
(Session info: chrome=54.0.2840.71)
(Driver info: chromedriver=2.25.426935 (820a95b0b81d33e42712f9198c215f703412e1a1),platform=Mac OS X 10.12.0 x86_64)
I'm using: Python 3.5.2 ,Chrome 54.0, chromedriver 2.25, selenium 3.0.1
I've tried other versions of chromedriver with no success, also I did not find any solution to this online. Thanks.
EDIT:
Still getting the error from above + getting a new error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__
desired_capabilities=desired_capabilities)
File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 92, in __init__
self.start_session(desired_capabilities, browser_profile)
File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 179, in start_session
response = self.execute(Command.NEW_SESSION, capabilities)
File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: session not created exception
from unknown error: bad inspector message: {"method":"Page.loadEventFired","params":{"timestamp":14220,088073}}
(Session info: chrome=54.0.2840.71)
(Driver info: chromedriver=2.25.426935 (820a95b0b81d33e42712f9198c215f703412e1a1),platform=Mac OS X 10.12.0 x86_64)
selenium.common.exceptions.TimeoutException: Message: timeout: cannot determine loading status
from timeout: Timed out receiving message from renderer: -0.003
Issue817:It looks like this issue has been logged as a bug for Selenium.
Someone has answered to get rid from this issue by using the --dns-prefetch-disable option of chrome.
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--dns-prefetch-disable')
driver = Chrome(chrome_options=chrome_options)
If issue still exists follow this thread may be it solves your problem
Set
env LANG=en_US.UTF-8 ./chromedriver
from : https://bugs.chromium.org/p/chromedriver/issues/detail?id=1552

Selenium error At the end of the page

I have written this code using selenium python so parse a webpage(dynamically loading) so
that it goes till the end and then stop when "load more" button is not clickable anymore.
wait=WebDriverWait(driver,50)
wait.until(EC.element_to_be_clickable((By.ID, 'bottomPager'))) while
EC.element_to_be_clickable((By.ID,'bottomPager')):
driver.find_element_by_xpath('.//div[#id="bottomPager"]').click()
if not driver.find_element_by_id('bottomPager').is_enabled():
break
wait.until(EC.element_to_be_clickable((By.ID,'bottomPager')))
but I am getting the error when it reaches the end of the page
Traceback (most recent call last): File "python_org_search2.py", line 24, in <module>
driver.find_element_by_xpath('.//div[#id="bottomPager"]').click() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 60, in click
self._execute(Command.CLICK_ELEMENT) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 370, in _execute
return self._parent.execute(command, params) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 166, in execute
self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 164, in check_response
raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: u'unknown error: Element is not clickable at point (643, 628)\n (Session info: chrome=34.0.1847.137)\n (Driver info: chromedriver=2.9.248304,platform=Linux 3.13.0-24-generic x86_64)'
What are the changes required in code so as to rectify it ?
In my experience, this exception only occurs when using the Chrome driver with Selenium. Can you use Firefox instead? (I believe Firefox is the primary intended browser for webdriver invocations via Selenium.)
driver = webdriver.Firefox()
That should clear up this exception.
(You can get portable versions of Firefox at this site.)

Categories

Resources