How to check if Open File dialog has been open after pressing a button in a Chrome Browser tab on Python? - python-3.x

I'm trying to automate a process within the OpenSea Create page after having logged in with Metamask, and so far, I have managed to develop a simple program that chooses a particular image file using a path which passes to the Open File dialog "implicitly", here's the code:
import pyautogui
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
def wait_xpath(code): #function to wait for the xpath of an element to be located
WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.XPATH, code)))
opt = Options() #the variable that will store the selenium options
opt.add_experimental_option("debuggerAddress", "localhost:9222") #this allows bulk-dozer to take control of your Chrome Browser in DevTools mode.
s = Service(r'C:\Users\ResetStoreX\AppData\Local\Programs\Python\Python39\Scripts\chromedriver.exe') #Use the chrome driver located at the corresponding path
driver = webdriver.Chrome(service=s, options=opt) #execute the chromedriver.exe with the previous conditions
nft_folder_path = r'C:\Users\ResetStoreX\Pictures\Cryptobote\Cryptobote NFTs\Crypto Cangrejos\SANDwich\Crabs'
start_number = 3
if driver.current_url == 'https://opensea.io/asset/create':
print('all right')
print('')
print(driver.current_window_handle)
print(driver.window_handles)
print(driver.title)
print('')
nft_to_be_selected = nft_folder_path+"\\"+str(start_number)+".png"
wait_xpath('//*[#id="main"]/div/div/section/div/form/div[1]/div/div[2]')
imageUpload = driver.find_element(By.XPATH, '//*[#id="main"]/div/div/section/div/form/div[1]/div/div[2]').click() #click on the upload image button
print(driver.current_window_handle)
print(driver.window_handles)
time.sleep(2)
pyautogui.write(nft_to_be_selected)
pyautogui.press('enter', presses = 2)
Output:
After checking the URL, the program clicks on the corresponding button to upload a file
Then it waits 2 seconds before pasting the image path into the Name textbox, for then pressing Enter
So the file ends up being correctly uploaded to this page.
The thing is, the program above works because the following conditions are met before execution:
The current window open is the Chrome Browser tab (instead of the Python program itself, i.e. Spyder environment in my case)
After clicking the button to upload a file, the Name textbox is selected by default, regardless the current path it opens with.
So, I'm kind of perfectionist, and I would like to know if there's a method (using Selenium or other Python module) to check if there's an Open File dialog open before doing the rest of the work.
I tried print(driver.window_handles) right after clicking that button, but Selenium did not recognize the Open File dialog as another Chrome Window, it just printed the tab ID of this page, so it seems to me that Selenium can't do what I want, but I'm not sure, so I would like to hear what other methods could be used in this case.
PS: I had to do this process this way because send_keys() method did not work in this page

The dialog you are trying to interact with is a native OS dialog, it's not a kind of browser handler / dialog / tab etc. So Selenium can not indicate it and can not handle it. There are several approaches to work with such OS native dialogs. I do not want to copy - paste existing solutions. You can try for example this solution. It is highly detailed and looks good.

Related

Avoid download pop up in python3 using serelinum Download pdf

Object:
automate following process.
1. Open particular web page, fill the information in search box, submit.
2. from search results click on first result and download the PDF
Work done:
To reach to this object I have written a code as first step. The code works fine but opens up download pop up. Till the time I can't get rid of it, I can not automate the process further. Searched for very many solutions. But none has worked.
For instance, This solution is hard for me to understand and I think its more to do with Java then Python. I changed fire fox profile as suggested by many. This dose matches though not exactly same. I haven't tried as there is no much difference. Even this speaks about changing fire fox profile but that doesn't work.
My code is as below
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
from time import sleep
import time
import wget
from wget import download
import os
#set firefox Profile
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference("browser.download.manager.showAlertOnComplete", False)
profile.set_preference('browser.download.dir', os.getcwd())
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/pdf')
#set variable driver to open firefox
driver = webdriver.Firefox(profile)
#set variable webpage to open the expected URL
webpage = r"https://documents.un.org/prod/ods.nsf/home.xsp" # edit me
#set variable to enter in search box
searchterm = "A/HRC/41/23" # edit me
#open the webpage with get command
driver.get(webpage)
#find the element "symbol", insert data and click submit.
symbolBox = driver.find_element_by_id("view:_id1:_id2:txtSymbol")
symbolBox.send_keys(searchterm)
submit = driver.find_element_by_id("view:_id1:_id2:btnRefine")
submit.click()
#list of search results open up and 1st occarance is clicked by coppying its id element
downloadPage = driver.find_element_by_id("view:_id1:_id2:cbMain:_id135:rptResults:0:linkURL")
downloadPage.click()
#change windiows. with sleep time
window_before = driver.window_handles[0]
window_after = driver.window_handles[1]
time.sleep(10)
driver.switch_to.window(window_after)
#the actual download of the pdf page
theDownload = driver.find_element_by_id("download")
theDownload.click()
Please guide.
The "Selections" popup is not a different window/tab, it's just an HTML popup. You can tell this because if you right click on the dialog, you will see the normal context menu. You just need to make your "Language" and "File type(s)" selections and click the "Download selected" button.

How to click the Continue button using Selenium and Python

I'm trying to automate some tedious copy / paste I do monthly from my bank's online service via Selenium and Python 3. Unfortunately, I can't get Selenium to click the log-in link.
It's the blue continue button at https://www1.bmo.com/onlinebanking/cgi-bin/netbnx/NBmain?product=5.
Strangely, when I try to click that link manually in the browser launched by Selenium, it doesn't work either - whereas it does work in a browser I launch manually.
I suspect the issue is that the bank's website is smart enough to detect that I'm automating the browser activity. Is there any way to get around that?
If not, could it be something else?
I've tried using Chrome and Firefox - to no avail. I'm using a 64 bit Windows 10 machine with Chrome 73.0.3683.103 and Firefox 66.0.
Relevant code is below.
#websites and log in information
bmo_login_path = 'https://www1.bmo.com/onlinebanking/cgi-bin/netbnx/NBmain?product=5'
bmo_un = 'fake_user_name'
bmo_pw = 'fake_password'
#Selenium setup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
chrome_driver_path = 'C:\\Path\\To\\Driver\\chromedriver.exe'
gecko_driver_path = 'C:\\Path\\To\\Driver\\geckodriver.exe'
browswer_bmo = webdriver.Firefox(executable_path = gecko_driver_path)
#browswer_bmo = webdriver.Chrome(executable_path = chrome_driver_path)
#log into BMO
browswer_bmo.get(bmo_login_path)
time.sleep(5)
browswer_bmo.find_element_by_id('siBankCard').send_keys(bmo_un)
browswer_bmo.find_element_by_id('regSignInPassword').send_keys(bmo_pw)
browswer_bmo.find_element_by_id('btnBankCardContinueNoCache1').click()
Sending the keys works perfectly. I may actually have the wrong element ID (I was trying to test that in Chrome when I realized I couldn't click the link manually) - but I think the bigger issue is that I can't manually click the link in the browser launched by Selenium. Thank you for any ideas.
EDIT
This is a screenshot that I get of all I get when I try to click the continue button.
Ultimately the error message I get in my IDE (Jupyter Notebook) is:
TimeoutException: Message: timeout
(Session info: chrome=74.0.3729.108)
(Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729#{#29}),platform=Windows NT 10.0.17134 x86_64)
To click on the button with text as Continue you can fill up the Card Number and Password field inducing WebDriverWait for the element_to_be_clickable() and you can use the following solution:
Code Block:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument('start-maximized')
options.add_argument('disable-infobars')
options.add_argument('--disable-extensions')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get('https://www1.bmo.com/onlinebanking/cgi-bin/netbnx/NBmain?product=5')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.dijitReset.dijitInputInner#siBankCard[name='FBC_Number']"))).send_keys("1234567890112233")
driver.find_element_by_css_selector("input.dijitReset.dijitInputInner#regSignInPassword[name='FBC_Password']").send_keys("fake_password")
driver.find_element_by_css_selector("span.dijitReset.dijitInline.dijitIcon.dijitNoIcon").click()
# driver.quit()
Browser Snapshot:
I was able to fix this issue and solve the problem by adding the following line below the options variables. This disables the chrome check for automation. I used the whole sale code and then added the following line in the correct location before starting the driver.
options.add_experimental_option("excludeSwitches", ['enable-automation'])
ref: https://help.applitools.com/hc/en-us/articles/360007189411--Chrome-is-being-controlled-by-automated-test-software-notification

I want to right click and open link in new tab using selenium with python

from selenium.webdriver import ActionChains
action = ActionChains(driver)
action.context_click(driver.find_element_by_id('id')).perform()
it's doing a right click for me but unable to perform further action.like open link in new tab using python
First off, we import our packages:
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys
from time import sleep
Let's do it:
browser = webdriver.Firefox()
browser.get('https://www.google.com?q=python#q=python')
first_result = ui.WebDriverWait(browser, 15).until(lambda browser: browser.find_element_by_class_name('rc'))
first_link = first_result.find_element_by_tag_name('a')
# Save the window opener (current window, do not mistaken with tab... not the same)
main_window = browser.current_window_handle
# Open the link in a new tab by sending key strokes on the element
# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack
first_link.send_keys(Keys.CONTROL + Keys.RETURN)
# Switch tab to the new tab, which we will assume is the next one on the right
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
# Put focus on current window which will, in fact, put focus on the current visible tab
browser.switch_to_window(main_window)
# do whatever you have to do on this page, we will just got to sleep for now
sleep(2)
# Close current tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
# Put focus on current window which will be the window opener
browser.switch_to_window(main_window)
As discussed with you.I have tried to open a create page on Facebook as a new window using right click options.Here is the code.Hope this help you.
driver = webdriver.Chrome('D:/Java/TestChrome/lib/chromedriver.exe')
driver.get("https://www.facebook.com/")
element=driver.find_element_by_xpath("//a[text()[contains(.,'Create a Page')]]")
#Open in new window to click on Create page using right click
ActionChains(driver).context_click(element).key_down(Keys.CONTROL).click(element).perform()
Let me know if it works.

using Python's webdriver to click an element

Python code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.policybazaar.com/")
btn = driver.find_element_by_xpath('//a[#class="circleTab v3health"]')
btn.click
I want to click the "Health" button under the above mentioned website, but it gives me an error:
bound method WebElement.click of
selenium.webdriver.firefox.webelement.FirefoxWebElement(session="b30bbdb3
4401-40ab-9827-6fd0d554de50", element="c744a45a-e7ee-419c-9a46-
bf522ed4f2e2"
When I inspect element, I found this:
Content
What should be correct approach to make the script click health button?
Button click is a function, call it with brackets
btn.click()
You may also like to wait for the page to load see Wait until page is loaded with Selenium WebDriver for Python or
import time
....
time.sleep (10) # before you call the click function

How to handle multiple windows in Python selenium with Firefox driver

I want to learn WINDOW handling in Python Selenium.
My Task is:
First open 'Google.com'.
Second open 'Yahoo.com' in New Window.
Third switch back to First Window and click on Gmail Link.
Fourth switch to Second Window and click on Finance Link.
Following Code works for me:
browser.get("http://www.google.co.in")
browser.execute_script("window.open('https://www.yahoo.com')")
browser.switch_to_window(browser.window_handles[0])
print(browser.title)
gmail=browser.find_element_by_class_name("gb_P")
gmail.click()
browser.switch_to_window(browser.window_handles[1])
print(browser.title)
fin=browser.find_element_by_link_text("Finance")
fin.click()
But when I try to change sequence to task as:
First open 'Google.com'.
Second open 'Yahoo.com' in New Window.
Third remaining in same window and click on Finance Link.
Fourth switch to First Window and click on Gmail Link.
The below altered code for the task in which after opening yahoo.com in new window and then clicking on finance link and then switching to main window containing Google.com then clicking on Gmail link doesn't work:
browser.get("http://www.google.co.in")
browser.execute_script("window.open('https://www.yahoo.com')")
browser.switch_to_window(browser.window_handles[1])
print(browser.title)
fin=browser.find_element_by_link_text("Finance")
fin.click()
browser.switch_to_window(browser.window_handles[0])
print(browser.title)
gmail=browser.find_element_by_class_name("gb_P")
gmail.click()
But if I refresh the page after switching to the Yahoo tab this works only in Chrome Driver and not in Firefox Driver.
browser.get("http://www.google.co.in")
print(browser.current_window_handle)
browser.execute_script("window.open('https://www.yahoo.com')")
print(browser.current_window_handle)
WebDriverWait(browser, 10).until(EC.number_of_windows_to_be(2))
browser.switch_to_window(browser.window_handles[1])
print(browser.current_window_handle)
print(browser.title)
browser.refresh()
fin=browser.find_element_by_link_text("Finance")
fin.click()
print(browser.window_handles)
WebDriverWait(browser,10000)
browser.switch_to_window(browser.window_handles[0])
print(browser.title)
print(browser.current_window_handle)
gmail=browser.find_element_by_class_name("gb_P")
gmail.click()
As per your updated question a few words about Tab/Window switching/handling:
Always keep track of the Parent Window handle so you can traverse back for the rest of your usecases.
Always use WebDriverWait with expected-conditions as number_of_windows_to_be(num_windows)
Always keep track of the Child Window handles so you can traverse back if required.
Here is your own code with some minor tweaks mentioned above:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#other lines of code
browser.get("http://www.google.co.in")
print("Initial Page Title is : %s" %browser.title)
windows_before = browser.current_window_handle
print("First Window Handle is : %s" %windows_before)
browser.execute_script("window.open('https://www.yahoo.com')")
WebDriverWait(browser, 10).until(EC.number_of_windows_to_be(2))
windows_after = browser.window_handles
new_window = [x for x in windows_after if x != windows_before][0]
# browser.switch_to_window(new_window) <!---deprecated>
browser.switch_to.window(new_window)
print("Page Title after Tab Switching is : %s" %browser.title)
print("Second Window Handle is : %s" %new_window)
Console Output:
Initial Page Title is : Google
First Window Handle is : CDwindow-34D74AB1BB2F0A1A8B7426BF25B86F52
Page Title after Tab Switching is : Yahoo
Second Window Handle is : CDwindow-F3ABFEBE4907CFBB3CD09CEB75ED570E
Browser Snapshot:
Now you have got both the Window Handles so you can easily switch to any of the TABs to perform any action.

Resources