Closing a generic pop up in Selenium - python

While scraping a page using selenium webdriver, there is a "pop up" that appears .
On Opening the page, http://www.fanatics.com/search/red%20shoes - I see a popup window with xpath '//*[#id="mm_DesktopInterstitialImage"]' - but I don't want to be using the xpath to close this alert, and have something genric that can dismiss/close the alert.
Here's what I tried so far -:
from selenium import webdriver
import os
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
chromedriver = "/usr/local/CHROMEDRIVER"
desired_capabilities=DesiredCapabilities.CHROME
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver,desired_capabilities=desired_capabilities)
url='http://www.fanatics.com/search/red%20shoes'
driver.get(url)
#driver.set_page_load_timeout(300)
driver.implicitly_wait(60)
alert = driver.switch_to_alert()
alert.dismiss
handle=driver.window_handles
print handle
#[u'CDwindow-B1E9C127-719D-ACAA-19DE-1A6FA265A4FF']
From what I understand from related examples, folks usually switch window handles, but my handle has a single element.i.e, driver.switch_to_window(driver.window_handles[1]) then driver.close() and finally shift again, using driver.switch_to_window(driver.window_handles[1]) I also used implicit wait, since I was not sure, if the alert window was being read at-all - but that did not work either. I do not wnat to hard-code for the xpath,if that is possible.
What am I doing wrong ?
Related, but does't work for me : Selenium python how to close a pop up window?

As I can see, it's not an alert box!!. It is just a Simple Pop-up that appears when you are entering the page and it is present in main window itself(no need of switching and closing it too). Use the below code to close it.
driver.find_element_by_xpath('//div[contains(#class,"ui-dialog") and #aria-describedby="dialogContent2"]//button[#title="Close"]').click()

It works perfectly, give it a try ;)
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--disable-notifications")
browser = webdriver.Chrome('C:\Python34\Lib\site-packages\selenium\webdriver\chromedriver.exe', chrome_options=options)

The popup you are trying to close is not a browser alert but a DOM popup. A browser alert is a dialog box that the browser creates at the OS level. (It is appears as an additional window on your desktop.) You can use .switch_to_alert() to close these alerts. A DOM popup is just an HTML element that happens to be used the the page as if it were a dialog box. This popup has existence only in your browser. (The OS does not know about it.) You cannot use .switch_to_alert() to close DOM popups.
To get this popup and close it, you have to inspect the DOM (like you've started doing), find the DOM element that represents the close button and have Selenium click it.

I ran into a similar problem, except that our pop-up's closebox webelement had a dynamic id tag, making it difficult to latch onto. We ended up solving it by using By.className to find it. In the code below, I use a List because I was also looking to see how many elements I was dealing with, but that's not required. Also, the production code has additional handling in case window closebox elements were found.
List<WebElement> closeboxes = driver.findElements(By.className("v-window-closebox"));
for (WebElement we : closeboxes) {
we.click();
}

You can try the following:
from selenium.webdriver import ActionChains, Chrome
driver = Chrome('/usr/local/CHROMEDRIVER')
ActionChains(driver).move_to_element_with_offset(
driver.find_element_by_xpath('//html'), 0, 2338
).click().perform()
This will click an area outside of the popup thus closing it. 🤠

Related

The way to show mouse cursor using selenium in python

I tried to click on chrome browser while using ActionChains.
from selenium.webdriver import ActionChains
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(URL)
link = driver.find_element_by_id('link')
action = ActionChains(driver)
action.double_click(advanced_options_link).perform()
But what is more?!
I want to see mouse cursor on browser to monitor what is exactly happening.
*** Please help ***
I needed to use a function like this in the past. as far as Iv'e researched I learned that it's not possible with selenium. you can hover on elements or even move the cursor to a specific location on the scree, but you can't see it moving because it's not really moving the cursor, selenium dose not have control over the cursor in that fashion.
You can try to research this, you might be able to use something outside selenium to control the actual cursor of the computer. but, even if it's possible it will still be very hard to get it to work reliably because you don't have the control on the website that you have with selenium so everything becomes manual, therefore hard and keen to generate errors.
Does it work if you try using the move_to_element() from ActionChains? something like this;
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get(URL)
link = driver.find_element_by_id('link')
hover = ActionChains(driver).move_to_element(link)
hover.perform()

selenium How to dismiss a chrome popup

I tried anything I could find on this but I can't get selenium to dismiss this alert. I don't think it's an alert anymore though, as I get NoAlertPresentException when I try
driver.switch_to.alert.dismiss()
Any ideas?
Here are relevant parts of the HTML page:
<iframe id="teamsLauncher" src="msteams:/l/team/19:95f3ef22a37040fca83b679b64f96da1#thread.tacv2/conversations?groupId=09988212-e3a1-4187-b067-a805e512e0a4&tenantId=d348f9ab-4879-4a60-ab50-5c420b11470c&deeplinkId=2deee564-c6b3-4d5d-b097-93900dd14620&launchAgent=join_launcher&type=team&directDl=true&msLaunch=true&enableMobilePage=true&fqdn=teams.microsoft.com" style="display: none;"></iframe>
<script>var modernBrowser="fetch"in window&&"assign"in Object&&"Set"in window,bundles=[],polyfills="";function injectScript(n,e,s){var t=document.createElement("script");t.src=n,t.async=e,t.onload=s,document.body.appendChild(t)}function loadBundles(n){for(key in bundles)injectScript(bundles[key],n)}function loadPolyfills(){polyfills&&injectScript(polyfills,!1,function(){loadBundles(!1)})}bundles.push("https://statics.teams.microsoft.com/hashedjs-launcher/launcher.5c24f1e70f34f56835c7.js"),polyfills="https://statics.teams.microsoft.com/hashedjs-launcher/polyfills.1e46ca6473519cf1be5d.js",modernBrowser?loadBundles(!0):loadPolyfills(),window.addEventListener("load",function(){injectScript("https://az725175.vo.msecnd.net/scripts/jsll-4.js",!0,function(){var n={coreData:{appId:"JS:teams.microsoft.com",market:window.navigator.language||"en-US"}};awa&&awa.init&&awa.init(n)})})</script>
Also tried actionchains, but sending escape key doesn't do anything.
Hard to say without running the code, but maybe try disabling chrome popups with Chrome Options?
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-notifications")
driver = webdriver.Chrome(options=chrome_options)
I hope, this works.
Consider using the library pyAutoGUI, it allows python to control your mouse and keyboard. If you keep the window in the same place each time, a static x y coordinate for the mouse click function can be used to accept the popup and allow you to procced

How to switch between different chrome browser window opened by different WebDriver using selenium in Python?

I searched for this question,and I found an idea using driver.switch_to.window(),but it didn't work as expect:
from selenium import webdriver
driver1=webdriver.Chrome("D:\Python\Files\chromedriver.exe")
driver1.get('https://www.google.com')
driver2=webdriver.Chrome("D:\Python\Files\chromedriver.exe")
driver2.get('https://www.bing.com/')
driver1.switch_to.window(driver1.current_window_handle)
above code will first open a chrome window and go to google,then will open another chrome window and go to bing,then
driver1.switch_to.window(driver1.current_window_handle)
seems didn't work,the window showing bing still shows on top of the window showing google.
Anyone have any idea?I think
driver1.switch_to.window(driver1.current_window_handle)
may have some BUG.
As you have used two WebDriver instances as driver1 and driver2 respectively to openthe urls https://www.google.com (e.g. windowA) and https://www.bing.com/ (e.g. windowB) it is worth to mention that the function switch_to.window() is a WebDriver method. So, driver1 can control only windowA and driver2 can control only windowB.
For Selenium to interact with any of the Browsing Window, Selenium needs focus. So to iterate among the different Browsing Windows you can shift the focus to the different Browsing Window using JavascriptExecutor as follows :
Python:
driver1.execute_script("window.focus();")
driver2.execute_script("window.focus();")
Java:
((JavascriptExecutor) driver1).executeScript("window.focus();");
((JavascriptExecutor) driver2).executeScript("window.focus();");
I believe you have a different concept of "window" in driver.switch_to.window(). In chrome browser, it means "tab". It's not another chrome browser or browser window like what are you trying to do in your code.
If switch_to.window() what you really want, I'll give an example how to use it:
driver=webdriver.Chrome("D:\Python\Files\chromedriver.exe")
driver.get('https://www.google.com')
# open a new tab with js
driver.execute_script("window.open('https://www.bing.com')")
driver.switch_to.window(driver.window_handles[-1])
# now your driver is pointed to the "tab" you just opened

Python and selenium : firefox keep creating dialog boxes when downloading even if i set its preferences

I wrote a program using selenium and firefox web driver.
def dowloadFile(link):
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', '/tmp')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk',
'application/pdf')
driver = webdriver.Firefox(profile)
#driver.set_window_position(-10000,0)
driver.get(link)
s = BeautifulSoup(driver.page_source, "html.parser")
st=s.find('div',{"class":"bloc-docs-link bloc-250"})
#print("hadiii ST: "+str(st))
x=st.find('a')
fm=x.get('href')
fm="https://www.marchespublics.gov.ma/"+fm
driver.get(fm)
driver.quit()
my function takes as parameter a link, after that it gets that link and finally find another one which downloads the file.
my problem is, even if I set preferences of my firefox, it always keep showing dialog boxes when downloading, to confirm if i want to save it! I dont know what to do so I can download the file without this dialog box.
Any help please. Thank you in advance.
I've had issues with that too. I've just done this instead. Note: it does take more time so if you have a ton of files you're downloading, this may not be worth it. Otherwise, this will do the trick.
Create an alert object that's ready to be used on the dialogue boxes, like this for example:
alert = driver.switch_to_alert()
Import Expected Conditions:
from selenium.webdriver.support import expected_conditions as EC
Then, create a function that directs the browser to wait until the expected condition (the alert) is prompted.
WebDriverWait(browser, 3).until(EC.alert_is_present()
except TimeoutException:
It's best to put this is a try/except block, but not mandatory.
Then, simply use the 'accept' method of the alert object to confirm the download after selenium has taken control of the alert window:
alert.accept()
The function could look something like this:
try:
alert = driver.switch_to_alert()
alert_wait()
alert.accept()
except print('No alertfound')
Also, I would highly recommend using the requests/BeautifulSoup module for this so you don't have to render the browser and experience the delays that come with navigating through a ton of web pages. The requests module does it all behind the scenes. This gets tricky if you need to enter a password prior to downloading. If not, the BeautifulSoup library is awesome for scraping tags/hrefs, collecting them in a list, and then looping over them one by one using the similar requests.get() method.
In fact, the last time I had this problem, I used the requests module instead of selenium and the alert windows were automatically accepted. Lightening fast, too.
First of all, why are you using beautifulsoup?! Make use of driver.find_element_by_css_selector
Secondly, please confirm that the PDF file you're targetting actually has the appropriate mimetype. See http://yizeng.me/2014/05/23/download-pdf-files-automatically-in-firefox-using-selenium-webdriver/

Is it possible to have the new window opened in selenium, focus as the primary window on your screen?

I'm new to selenium.
I have tried many answers on stack overflow including:
Get focus on the new window in Selenium Webdriver and Python
and
Make sure that browser opened by webdriver is always in focus
None of the questions i have seen seem to work for me.
I'm using python 3.5 and the latest selenium. The window opens and executes anything I tell however it's in the background and never focuses. Is there something I'm missing?
I have tried iterating over the windows and focusing each one but none of this works.
I would really like this to happen as watching the browser as the script executes is the reason why i'm using this tool.
Any suggestions are welcome.
Thanks.
AFAIK you cannot control visibility of content of each opened tab/window automatically. However, you can handle last opened tab/window as below and see what exactly happens on current tab/window:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.google.com")
google_window = driver.current_window_handle # Define main window
print(driver.title) # Title now is "Google". It is currently visible
driver.execute_script("window.open('http://www.bing.com');") # Open Bing window
bing_window = [window for window in driver.window_handles if window != google_window][0] # Define Bing window
driver.switch_to_window(bing_window)
print(driver.title) # Title now is "Bing". It is currently visible
driver.execute_script("window.close();") # Close Bing window
driver.switch_to_window(google_window)
print(driver.title) # Now title is again "Google". It is currently visible
Also you can use driver.get(URL) to open new page in current window and navigate in history with driver.back() and driver.forward()

Categories