How to dismiss print dialog in selenium? - python

I am trying to render a page which on load automatically shows the print dialog. I want to skip it using selenium. I searched on internet but couldn't find any suitable example since most of example handles javascript alert not windows alert.
I also install python robotframework because many people suggested it but couldn't find any example for that either.
My question is how to dismiss windows alert using selenium and robotframework in python?
NOTE: This question is in continuation of my previous question. python selenium not updating pop up window url

I could avoid the printing window by overriding the window.print function:
driver.execute_script("window.print = function(){};")

Using Firefox you could set some profile options that effectively silence the print dialog popup.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
profile = webdriver.FirefoxProfile()
profile.set_preference("print.always_print_silent", True)
profile.set_preference("print.show_print_progress", False)
driver = webdriver.Firefox(profile)
driver.get("http://www.google.com")
# Send print instruction
elem = driver.find_element_by_xpath("//body")
elem.send_keys(Keys.COMMAND, "p")

Related

Selenium get session ID of new window - Python

I am using Selenium in order to perform some checks on Chrome.
I'm automatically browsing to "chrome://flags/#enable-quic" and there in the drop down I (automatically) choose "Enable".
As written below, one has to relaunch in order for the changes to take effect.
I want to open a new tab on the new re-launched window to do some more stuff.
A snip of the code:
browser = webdriver.Chrome()
browser.get("chrome://flags/#enable-quic")
browser.find_element_by_xpath("//*[#id='enable-quic']/table/tbody/tr/td/div[1]/div/div[2]/select/option[2]").click() #Select "Enable"
time.sleep(5)
browser.find_element_by_xpath("//*[#id='flagsTemplate']/div[5]/button").click() #Click relaunch
time.sleep(5)
browser.execute_script("window.open('https://www.gmail.com');") #Exception after this line
The exception I get is:
selenium.common.exceptions.NoSuchWindowException: Message: no such window: window was already closed
Someone has an idea how to handle this?
Thanks
After clicking "Refresh" button you get new Chrome window. You should try to switch to that window before executing JavaScript:
browser = webdriver.Chrome()
browser.get("chrome://flags/#enable-quic")
browser.find_element_by_xpath("//div[#id='enable-quic']//select[#class='experiment-select']/option[2]").click()
time.sleep(5)
browser.find_element_by_xpath("//button[#class='experiment-restart-button']").click()
time.sleep(5)
browser.switch_to.window(browser.window_handles[0])
browser.execute_script("window.open('https://www.gmail.com');")
re-launching Chrome is a bad idea because Chromedriver has a reference to the original chrome process.
no such window: window was already closed
so... browser is still pointing to the old window.
Instead of trying to relaunch Chrome, just set the option when you create a Chromedriver instance.
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--enable-quic')
chrome = webdriver.Chrome(chrome_options=chrome_options)

Send keys control + click in Selenium with Python bindings

I need to open link in new tab using Selenium.
So is it possible to perform ctrl+click on element in Selenium to open it in new tab?
Use an ActionChain with key_down to press the control key, and key_up to release it:
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('http://google.com')
element = driver.find_element_by_link_text('About')
ActionChains(driver) \
.key_down(Keys.CONTROL) \
.click(element) \
.key_up(Keys.CONTROL) \
.perform()
time.sleep(10) # Pause to allow you to inspect the browser.
driver.quit()
Two possible solutions:
opening a new tab
self.driver = webdriver.Firefox()
self.driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
this is the solution for MAC OSX. In other cases you can use the standard Keys.CONTROL + 't'
opening a new webdriver
driver = webdriver.Firefox() #1st window
second_driver = webdriver.Firefox() #2nd windows
Below is what i have tried for Selenium WebDriver with Java binding and its working for me.
If you want to manually open the Link in New Tab you can achieve this by performing Context Click on the Link and selecting 'Open in new Tab' option. Below is the implementation in Selenium web-driver with Java binding.
Actions newTab= new Actions(driver);
WebElement link = driver.findElement(By.xpath("//xpath of the element"));
//Open the link in new window
newTab.contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
Web-driver handles new tab in the same way to that of new window. You will have to switch to new open tab by its window name.
driver.switchTo().window(windowName);
You can keep track of window-names which will help you to easily navigate between tabs.
By importing Keys Class, we can open page in new tab or new window with CONTROL or SHIFT and ENTER these keys:
driver.find_element_by_xpath('//input[#name="login"]').send_keys(Keys.CONTROL,Keys.ENTER)
or
driver.find_element_by_xpath('//input[#name="login"]').send_keys(Keys.SHIFT,Keys.ENTER)
For python, a good solution would be driver.find_element_by_css_selector('<enter css selector here>').send_keys(Keys.CONTROL, Keys.RETURN)
After that, you should change windows so selenium could function in the new window
window_before = driver.window_handles[0]
window_after = driver.window_handles[1]
driver.switch_to_window(window_after)
After using the window is useful to close it or go back to the original:
Close tab: driver.close()
Back to the original: driver.switch_to_window(window_before)
Also try driver.switch_to.window() if your Selenium version does not support the other one
Following is working for me to open link in new tab :
String link = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.linkText("yourlinktext")).sendKeys(link);
Above code is in java. you can convert to python easily I assume.
Please ask if have any query.

PhantomJS does not navigate to the next page after clicking a link

I am having a strange issue with PhantomJS or may be I am newbie. I am trying to login on NewEgg.com via Selenium by using PhantomJS. I am using Python for it. Issue is, when I use Firefox as a driver it works well but as soon as I set PhantomJS as a driver it does not go to next page hence give message:
Exception Message: u'{"errorMessage":"Unable to find element with id \'UserName\'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"89","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:55372","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method":"POST","post":"{\\"using\\": \\"id\\", \\"sessionId\\": \\"aaff4c40-6aaa-11e4-9cb1-7b8841e74090\\", \\"value\\": \\"UserName\\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/aaff4c40-6aaa-11e4-9cb1-7b8841e74090/element"}}' ; Screenshot: available via screen
The reason I found after taking screenshot that phantom could not navigate the page and script got finished. How do I sort this out? Code Snippet I tried given below:
import requests
from bs4 import BeautifulSoup
from time import sleep
from selenium import webdriver
import datetime
my_username = "user#mail.com"
my_password = "password"
driver = webdriver.PhantomJS('/Setups/phantomjs-1.9.7-macosx/bin/phantomjs')
firefox_profile = webdriver.FirefoxProfile()
#firefox_profile.set_preference('permissions.default.stylesheet', 2)
firefox_profile.set_preference('permissions.default.image', 2)
firefox_profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
#driver = webdriver.Firefox(firefox_profile)
driver.set_window_size(1120, 550)
driver.get('http://newegg.com')
driver.find_element_by_link_text('Log in or Register').click()
driver.save_screenshot('screen.png')
I even put sleep but it is not making any difference.
I experienced this with PhantomJS when the content type of the second page is not correct. A normal browser would just interpret the content dynamically, but Phantom just dies, silently.

Does anybody know how to launch the print dialog from chrome by selenium+python

I have a question about how to launch the print dialog from chrome browser. I know the shortcut key to open this is ctrl+p, but I don't know how to describe it in selenium. Does anyone know this? Thanks a lot!
I tried the following code, but it doesn't work on my Chrome browser.
actions = ActionChains(driver)
actions.move_to_element(driver.find_element_by_tag_name('body'))
actions.key_down(Keys.CONTROL).send_keys('T').key_up(Keys.CONTROL).perform()
Basically you need to trigger the JavaScript function that triggers the print pop-up. That function is window.print().
So what you need is to trigger that function after arriving at the page you want to print.
So say you want to print the front page of stackoverflow.com
driver.get("https://stackoverflow.com")
# now you're at the page you want to print. Trigger print function
driver.execute_path("window.print()")
Now it should prompt you to the print pop-up. The reason you need to trigger the JavaScript function is because JavaScript is the browser's language.
Not quite what you are asking about, but this is what worked for me in Firefox.
Send CTRL+P (or COMMAND+P on mac) to the body element using ActionChains:
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://google.com")
actions = ActionChains(driver)
actions.move_to_element(driver.find_element_by_tag_name('body'))
actions.key_down(Keys.CONTROL).send_keys('p').key_up(Keys.CONTROL)
actions.perform()
driver.get("https://stackoverflow.com")
driver.execute_script("window.print()")

How to perform right click using Selenium ChromeDriver?

I have been searching for this a lot, but could not find an answer for Python.
Is it possible to simulate right click, or open up the context menu via selenium/chromedriver?
I have seen options for Java, and some other languages, but never in Python.
What would I have to do to simulate a right click on a link, or a picture?
It's called context_click in selenium.webdriver.common.action_chains. Note that Selenium can't do anything about browser level context menu, so I assume your link will pop up HTML context menu.
from selenium import webdriver
from selenium.webdriver import ActionChains
driver = webdriver.Chrome()
actionChains = ActionChains(driver)
actionChains.context_click(your_link).perform()
To move through the context menu we have to use pyautogui along with selenium. The reason for using pyautogui is that we need to have control of the mouse for controlling the options on the context menu. To demonstrate this, I am going to use a python code to automatically open a google image of Avengers Endgame in new tab.
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import pyautogui
URL = 'https://www.google.com/'
PATH = r'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
action = ActionChains(driver)
driver.get(URL)
search = driver.find_element_by_name('q')
search.send_keys('Avengers Endgame')
search.send_keys(Keys.RETURN)
image_tab = driver.find_element_by_xpath('//a[text()="Images"]')
image_tab.click()
required_image = driver.find_element_by_xpath('//a[#class="wXeWr islib nfEiy mM5pbd"]')
action.context_click(required_image).perform()
pyautogui.moveTo(120, 130, duration=1)
pyautogui.leftClick()
time.sleep(1)
pyautogui.moveTo(300,40)
pyautogui.leftClick()
Now in the above code, the part till pyautogui.moveTo(120, 130, duration=1) is selenium based. Your answer begins from pyautogui.moveTo(120, 130, duration=1) and what this does is simply moves the mouse button to the open image in new tab option of the context menu(Please note that the screen coordinates may vary based on your screen size). The next line clicks the option(using action.click().perform() won't work as expected).
The next two lines helps in navigating to the tab after it opens. Hope the code helps!
I encountered the same issue where I had to right-click and click on 'open link in new tab'.
I searched for a lot of answers on google but there was no specific solution I found for Python.
Earlier, I was doing using ActionChains where right-click menu is showing, but then that menu list can't be accessed in selenium as I found some threads saying this has OS-level access.
action = ActionChains(driver)
action.context_click(<obj_which_u_want_to_click>).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ENTER).perform()
Here, Keys.ARROW_DOWN is not working, and opening the link in the same tab, ideally, it should open in a new tab.
So, there are two ways through which I did this:
First, via send_keys:
link = driver.find_elements_by_xpath("//a[contains(#href, 'https:...')]")
link.send_keys(Keys.CONTROL + Keys.ENTER)
Second, through JavaScript:
driver.execute_script("window.open(arguments[0], '_blank');", link)
I think you can't access the right-click menu items in selenium as it is out of its scope.
You can perform context click using ActionChains, and use Arrows via send_keys to select an element from the context menu.
ActionChains(context.browser).move_to_element(element).context_click(element).perform()
ActionChains(context.browser).send_keys(Keys.ARROW_UP).perform()
ActionChains(context.browser).send_keys(Keys.ENTER).perform()

Categories

Resources