How do I interact with different windows simultaneously using Selenium? - python

from selenium import webdriver
browser = webdriver.Chrome(r"chromedriver.exe")
browser_2 = webdriver.Chrome(r"chromedriver.exe")
browser.get("https://www.seleniumhq.org/")
browser_2.get("https://www.seleniumhq.org/")
browser.find_element_by_id("menu_download").click()
browser_2.find_element_by_id("menu_download").click()
Is there a cleaner way to click on the download button in both windows or do I have to repeat the code for each instance of the browser?
I am making a program where I need to insert text, tick boxes ect in several instances of the same website and do not want to have to repeat the same code for each window.

Each browser is a different instance. You can not use a part of the code for both. So the answer is no. You cannot use another to do this. Your above code is correct though.

How about this:
path = 'chromedriver.exe'
n_drivers = 2
drivers = [webdriver.Chrome(path) for i in range(n_drivers)]
for driver in drivers:
driver.get('https://www.seleniumhq.org/')
driver.find_element_by_id('menu_download').click()

Related

How to interact with a separate pop-up window/website with Selenium / Chrome Driver in Python?

I am trying to automate a process with Selenium, and am having troubles figuring out how to switch between open windows while the program is running.
After clicking on the button, it opens another website that has a separate url, which is unique each time it is opened. I need to switch Selenium from interacting with the original website to this new popup within the browser, caused by the original website. The new window shows that it is also controlled by Chromedriver with the bit at the top that says "Chrome is being controlled by automated test software." Additionally, the actual website opened will be the same, just the fine print after the '.com/' is different.
How would I go about doing this? Also, how would I switch back? (If this is even possible)
For example:
driver=webdriver.Chrome(service=s)
driver.get("https://originalwebsite.com/")
driver.find_element(By.XPATH, 'buttons-xpath').click()
# (popup opens up now)
# *switch to popup website here*
driver.find_element(By.XPATH, 'button-on-new-website-xpath').click()
driver.find_element(By.XPATH, 'second-button-on-new-website-xpath').click()
# *popup website closes*
# switch back to original website / window
Thanks!
I have tried to use driver.navigate in a variety of ways but generally have no clue what I am doing. Thanks again!
The comment from ALex Break led to the answer.
All I had to do was:
handles = driver.window_handles
driver.switch_to.window(handles[x])
#handles[x] is the index of the list handles that has the handle I want to switch
#to stored in it

How to compare the screen to a screenshot in Python

I'm making a Python program that opens Target and buys an item entered by the user. If the item is unavailable, the program does nothing and prints a message in the console. To check if the item is available, I need to check if the screen includes something similar to a screenshot I took. The screenshot is shown below.
Can anyone help me with this?
Well, you sure can compare two screenshots, using library as matplotlib, PIL or opencv (or even numpy) but I guess the easiest path is to use selenium (if you automate your navigation) or beautifulsoup4/scrapy.
Something like :
from selenium import webdriver
browser = webdriver.Firefox()
url = "https://www.target.com/"
browser.get(url)
# navigate to find your product
out_of_stock_text = "put your stuff here"
if out_of_stock_text in browsers.page_source:
# Do your stuff here
Good luck !

{Python, Selenium} How can I detect browser windows that I'm already using and create a new tab inside said browser window?

I am currently working on a auto log-on for a website, but I found that selenium opens a new browser window each time I run the script. I want to make it so that it opens a new tab in the browser window I am already using. Selenium opens a new browser window, like so:
However, I want it to detect a window I am already using, and place a new tab there, like so:
Can we do this with Selenium for Python or do I need another language?
Sorry if my question is a bit stupid.
Thanks!
There are no stupid questions.
You need to find the reason why your selenium is opening new browser each time you log in.
It is probably because you are initialize webdriver each time you run that method.
Or maybe you use some hooks or tags which are triggering creation of new webdriver.
The code form other user from this site:
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
windows = driver.window_handles
time.sleep(3)
driver.switch_to.window(windows[1])

How to Navigate Context Menus (Selenium, Python)

I am aware that Selenium apparently doesn't support navigating context menus. But I have also seen in several other threads that there is a work-around by using action chains. Using context_click() followed by arrow key commands to navigate through the menus.
All examples I've seen have used Java, and when I translated to Python, only the context_click() command would register. Strangely enough, I wouldn't get an error either. Other sources have said that the context menus Selenium produces are only system level, and thus, Selenium cannot touch them, only create.
So my question is, has anyone been able to successfully navigate and chose options from context menus through Selenium? Python examples are preferred, but I'll take any advice or answers I can get.
Edit:
Code:
driver.get('https://www.google.com/')
actionChains = ActionChains(driver)
actionChains.context_click().send_keys(Keys.ARROW_UP).send_keys(Keys.ENTER).perform()
Context:
This is just a test script that I have been running to test this situation. In my personal project, I need to navigate the context menu to access a chrome extension. Since selenium can only interact within the web page I can't have it click on the button for the Chrome extension that is displayed by the browser. So this is the work-around I have been attempting.
Research:
https://testingrepository.com/how-to-right-click-using-selenium-webdriver/
- This source tells that seleniums context menus are only system level. In Java examples they also use a .build() command. As far as my knowledge, this command is not available to Python.
Select an Option from the Right-Click Menu in Selenium Webdriver - Java
- Thread suggesting that arrow key commands should work. However, all examples use Java and the .build() command as well
https://github.com/SeleniumHQ/selenium/blob/master/py/selenium/webdriver/common/action_chains.py
- shows that ActionChains() are Pythons's version of a .build() command. Might be common knowledge to some. I did not know this prior.
How to perform right click using Selenium ChromeDriver?
- very similar question to mine. While one user suggests that the menu cannot be interacted with, another suggests the actionChains work-around will work.
Thin,
I had the same problem and wonder nobody answered this already... It wasn't possible for me to solve it with selenium, cause selenium would navigate within the page. My solution:
import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
ActionChains(driver).move_to_element(element).context_click().perform()
wsh.SendKeys("{DOWN}") # send the keys you want
Well we can solve this using selenium along with pyautogui. 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!
one way to work around this I think at least in java is to perform those actions with one instance of the class Robot.
This is just an example of handling authentication in chromme. Is very usefull when I need to perform actions out the selenium scope.
try{
Robot bot = new Robot();
for(char c: userArray){
bot.keyPress(c);
bot.keyRelease(c);
bot.delay(300);
}
bot.keyPress(KeyEvent.VK_TAB);
bot.keyRelease(KeyEvent.VK_TAB);
for(char c: userArray){
bot.keyPress(c);
bot.keyRelease(c);
bot.delay(300);
}
bot.keyPress(KeyEvent.VK_ENTER);
bot.keyRelease(KeyEvent.VK_ENTER);
}catch(Exception e){
e.printStackTrace();
}

How to control Webpage dialog with python

When I try to automatically download a file from some webpage using Python,
I get Webpage Dialog window (I use IE). The window has two buttons, such as 'Continue' and 'Cancel'. I cannot figure out how to click on the Continue Button. The problem is
that I don't know how to control Webpage Dialog with Python. I tried to use
winGuiAuto to find the controls of the window, but it fails to recognize any Button type
controls... An ideas?
Sasha
A clarification of my question:
My purpose is to download stock data from a certain web site. I need to perform it for many stocks so I need python to do it for me in a repetitive way. This specific site exports the data by letting me download it in Excel file by clicking a link. However after clicking the link I get a Web Page dialog box asking me if I am sure that I want to download this file. This Web page dialog is my problem - it is not an html page and it is not a regular windows dialog box. It is something else and I cannot configure how to control it with python. It has two buttons and I need to click on one of them (i.e. Continue). It seems like it is a special kind of window implemented in IE. It is distinguished by its title which looks like this: Webpage Dialog -- Download blalblabla. If I click Continue mannually it opens a regular windows dialog box (open,save,cancel) which i know how to handle with winGuiAuto library. Tried to use this library for the Webpage Dialog window with no luck. Tried to recognize the buttons with Autoit Info tool -no luck either. In fact, maybe these are not buttons, but actually links, however I cannot see the links and there is no source code visible... What I need is someone to tell me what this Web page Dialog box is and how to control it with Python. That was my question.
You can't, and you don't want to. When you ask a question, try explaining what you are trying to achieve, and not just the task immediately before you. You are likely barking down the wrong path. There is some other way of doing what you are trying to do.
The title 'Webpage Dialog' suggests that is a Javascript-generated input box, hence why you can't access it via winGuiAuto. What you're asking directly is unlikely to be possible.
However, making the assumption that what you want to do is just download this data from the site, why are you using the GUI at all? Python provides everything you need to download files from the internet without controlling IE. The process you will want to follow is:
Download the host page
Find the url for your download in the page (if it changes)
Download the file from that url to a local file
In Python this would look something like this:
import urllib,re
f = urllib.urlopen('http://yoursitehere') # Original page where the download button is
html = f.read()
f.close()
m = re.search('/[\'"](.*\.xls)["\']/', html, re.S) # Find file ending .xls in page
if m:
urllib.urlretrieve(m.group(1), 'local_filename.xls') # Retrieve the Excel file
It is better to use selenium Python bindings:
from selenium import webdriver
from selenium.webdriver.common import alert
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
class AlertsManager:
def alertsManager(self,url):
self.url_to_visit=url
self.driver=webdriver.Ie()
self.driver.get(self.url_to_visit)
try:
while WebDriverWait(self.driver,1).until(EC.alert_is_present()):
self.alert=self.driver.switch_to_alert()
self.driver.switch_to_alert().accept()
except TimeoutException:
pass
if __name__=='__main__':
AM=AlertsManager()
url="http://htmlite.com/JS006.php" # This website has 2 popups
AM.alertsManager(url)

Categories

Resources