I'm looking at using Python and WinAppDriver to automate a clickonce application.
When the application starts, I get a dialog with a yes and no button on screen.
from appium import webdriver
class TestStuff(unittest.TestCase):
#classmethod
def setUpClass(self):
#set up appium
desired_caps = {}
desired_caps["app"] = r"<path to .appref-ms>"
self.driver = webdriver.Remote(command_executor='http://127.0.0.1:4723',desired_capabilities= desired_caps)
#classmethod
def tearDownClass(self):
self.driver.quit()
def test_initialize(self):
self.driver.find_element_by_name("No").click()
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestStuff)
unittest.TextTestRunner(verbosity=2).run(suite)
Now, when I run this script, I see my application launch - but then after a few seconds, I get an error **Failed to locate opened application window with appId: < path to the appref-ms > **
Not sure if this is an issue as a dialog is launching first, rather than the application? But can anyone suggest any other way to attach to the running application?
After a bit of digging about, I think I found what is wrong - this is to help in case any others get into this pickle.
So first, I've found a few places which say ClickOnce applications aren't supported.
So I decided to abandon executing the appref-ms and put in an .exe
This worked, but would throw a .NET error when I clicked on any buttons.
Launching the app from the command line was working also, I could not figure out why.
So I went back to the command line and tried to launch my app with the fully qualified path as the code does - click a button, .NET error.
It turns out you also need to add the "appWorkingDirectory" capability. Also (and this was my misunderstanding) you need to keep the full path in the launcher - I thought since I had the working directory set, I could just put the exe name - this was wrong.)
Related
I am trying to open a window application when it is not opened in the background. To do that, I need to check if the process is running in the background. I am using pymen to check if the calc.exe is running, and if it's not, I will use subprocess to open a new calc.exe window. However, the code that I am using is not detecting if my calc.exe is actually running or not. It will always be Calculator is Not Running...
from pymem import Pymem
try:
pm = Pymem('calc.exe')
print('Calculator Started And Is Running....')
except:
print ('Calculator Is Not Running....')
I believe that the code is going through the details tab as shown as below to check if calc.exe is running or not. However, I can't find it in here as well even though the calculator app is running.
The detail tab in Task Manager
App like Notepad and Chrome are working fine but calculator. I have no idea why it is not working for calculator.
From Microsoft Calculator Windows 10:
The Calculator in non-LTSC editions of Windows 10 is a Universal
Windows Platform app. In contrast, Windows 10 LTSC (which does not
include universal Windows apps) includes the traditional calculator,
but which is now named win32calc.exe. … Both the universal Windows
app and LTSC's win32calc.exe register themselves with the system as
handlers of a 'calculator:' pseudo-protocol. … All Windows 10
editions (both LTSC and non-LTSC) continue to have a calc.exe, which
however is just a stub that launches (via ShellExecute) the
handler that is associated with the 'calculator:' pseudo-protocol.
In other words, calc.exe is merely a wrapper which launches another executable:
import psutil
import subprocess
import time
def list_calc(phase):
print(phase)
for proc in psutil.process_iter():
if proc.name().startswith( PROCNAME):
print( proc.name())
print( proc.cmdline()[0])
if proc.name() == 'CalculatorApp.exe':
proc.kill()
PROCNAME = 'Calc'
list_calc('- before:')
calc = subprocess.Popen([PROCNAME+'.exe'])
time.sleep(3) # wait until calculator window appears
list_calc('- after:')
Result: ver && .\SO\75191242.py
Microsoft Windows [Version 10.0.19045.2486]
- before:
- after:
CalculatorApp.exe
C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_11.2210.0.0_x64__8wekyb3d8bbwe\CalculatorApp.exe
I've been working on a script to automate some things in chrome, and i've gotten stuck on the simplest task. How do I run a test to check if Chrome is currently running on my pc? I was previously using pywinautos find_windows, but that only checks the tab name.
something like:
def chrome_running():
if 'google-chrome' running:
return True
else:
return False
I'm willing to use any modules. Thanks!
Try psutil module as following:-
import psutil
def if_process_is_running_by_exename(exename='chrome.exe'):
for proc in psutil.process_iter(['pid', 'name']):
# This will check if there exists any process running with executable name
if proc.info['name'] == exename:
return True
return False
This is checked on Window machine. You can play around with the executable name to make it work on other OSs also. Reference:- https://pypi.org/project/psutil/
I want to open a website in my local computer's web browser (Chrome or Internet Explorer) using Python.
open("http://google.co.kr") # something like this
Is there a module that can do this for me?
The webbrowser module looks promising: https://www.youtube.com/watch?v=jU3P7qz3ZrM
import webbrowser
webbrowser.open('http://google.co.kr', new=2)
From the doc.
The webbrowser module provides a high-level interface to allow
displaying Web-based documents to users. Under most circumstances,
simply calling the open() function from this module will do the right
thing.
You have to import the module and use open() function. This will open https://nabinkhadka.com.np in the browser.
To open in new tab:
import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)
Also from the doc.
If new is 0, the url is opened in the same browser window if possible.
If new is 1, a new browser window is opened if possible. If new is 2,
a new browser page (“tab”) is opened if possible
So according to the value of new, you can either open page in same browser window or in new tab etc.
Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.
As the instructions state, using the open() function does work, and opens the default web browser - usually I would say: "why wouldn't I want to use Firefox?!" (my default and favorite browser)
import webbrowser as wb
wb.open_new_tab('http://www.google.com')
The above should work for the computer's default browser. However, what if you want to to open in Google Chrome?
The proper way to do this is:
import webbrowser as wb
wb.get('chrome %s').open_new_tab('http://www.google.com')
To be honest, I'm not really sure that I know the difference between 'chrome' and 'google-chrome', but apparently there is some since they've made the two different type names in the webbrowser documentation.
However, doing this didn't work right off the bat for me. Every time, I would get the error:
Traceback (most recent call last):
File "C:\Python34\programs\a_temp_testing.py", line 3, in <module>
wb.get('google-chrome')
File "C:\Python34\lib\webbrowser.py", line 51, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser
To solve this, I had to add the folder for chrome.exe to System PATH. My chrome.exe executable file is found at:
C:\Program Files (x86)\Google\Chrome\Application
You should check whether it is here or not for yourself.
To add this to your Environment Variables System PATH, right click on your Windows icon and go to System. System Control Panel applet (Start - Settings - Control Panel - System). Change advanced settings, or the advanced tab, and select the button there called Environment Varaibles.
Once you click on Environment Variables here, another window will pop up. Scroll through the items, select PATH, and click edit.
Once you're in here, click New to add the folder path to your chrome.exe file. Like I said above, mine was found at:
C:\Program Files (x86)\Google\Chrome\Application
Click save and exit out of there. Then make sure you reboot your computer.
Hope this helps!
Actually it depends on what kind of uses. If you want to use it in a test-framework I highly recommend selenium-python. It is a great tool for testing automation related to web-browsers.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")
I think it should be
import webbrowser
webbrowser.open('http://gatedin.com')
NOTE: make sure that you give http or https
if you give "www." instead of "http:" instead of opening a broser the interprete displays boolean OutPut TRUE.
here you are importing webbrowser library
I had this problem.When I define firefox path my problem had been solved.
import webbrowser
urL='https://www.python.org'
mozilla_path="C:\\Program Files\\Mozilla Firefox\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(mozilla_path))
webbrowser.get('firefox').open_new_tab(urL)
You can simply simply achieve it with any python module that gives you an interaction with command line(cmd) like subprocess, os, etc.
but here I came up with examples on only two modules.
Here is syntax (command) cmd /c start browser_name "URL"
Example
import os
# or open with iexplore
os.system('cmd /c start iexplore "http://your_url"')
# or open with chrome
os.system('cmd /c start chrome "http://your_url"')
__import__('subprocess').getoutput('cmd /c start iexplore "http://your_url"')
You can also run the command in the cmd it will work to or use other module call
click which mainly used for writing command line utilities.
here is how
import click
click.launch('http://your_url')
Its a 2 liner! :D
You are a great programmer so never give up!
#Use web-browser.
import webbrowser as w
w.open("https://google.com")
#remember to include https://
#If you want to make a page open if you click a button do this :
from tkinter import *
#^ Imports tk
import webbrowser as w
#^ Imports wb
x = Tk()
#Makes main window
def clicked() :
w.open("https://google.com")
#Defined the click function. (We'll use this later.)
link = Button(x, text="Click Me!", command=clicked)
link.pack(pady=20, padx=20)
#Our button
x.mainloop()
#Tkinter mainloop
If you want to open a specific browser (e.g. Chrome and Chromium) with command line options like full screen or kiosk mode and also want to be able to kill it later on, then this might work for you:
from threading import Timer
from time import sleep
import subprocess
import platform
# Hint 1: to enable F11 use --start-fullscreen instead of --kiosk, otherwise Alt+F4 to close the browser
# Hint 2: fullscreen will only work if chrome is not already running
platform_browser = {
'Windows': r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://stackoverflow.com',
'Linux' : ['/usr/bin/chromium-browser', '--kiosk', 'http://stackoverflow.com']
}
browser = None
def open_browser():
global browser
platform_name = platform.system()
if platform_name in platform_browser:
browser = subprocess.Popen(platform_browser[platform_name])
else:
print(":-(")
Timer(1, open_browser).start() # delayed start, give e.g. your own web server time to launch
sleep(20) # start e.g. your python web server here instead
browser.kill()
If you want to open any website first you need to import a module called "webbrowser". Then just use webbrowser.open() to open a website.
e.g.
import webbrowser
webbrowser.open('https://yashprogrammer.wordpress.com/', new= 2)
How can my Python script get the URL of the currently active Google Chrome tab in Windows? This has to be done without interrupting the user, so sending key strokes to copy/paste is not an option.
First, you need to download and install pywin32. Import these modules in your script:
import win32gui
import win32con
If Google Chrome is the currently active window, first get the window handle by:
hwnd = win32gui.GetForegroundWindow()
(Otherwise, find the Google Chrome window handle by using win32gui.FindWindow. Windows Detective is handy when finding out class names for windows.)
It seems the only way to get the URL is to get the text in the "omnibox" (address bar). This is usually the tab's URL, but could also be any partial URL or search string that the user is currently typing.
Also, the URL in the omnibox won't include the "http://" prefix unless the user has typed it explicitly (and not yet pressed enter), but it will in fact include "https://" or "ftp://" if those protocols are used.
So, we find the omnibox child window inside the current Chrome window:
omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)
This will of course break if the Google Chrome team decides to rename their window classes.
And then we get the "window text" of the omnibox, which doesn't seem to work with win32gui.GetWindowText for me. Good thing there's an alternative that does work:
def getWindowText(hwnd):
buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buf = win32gui.PyMakeBuffer(buf_size)
win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf)
return str(buf)
This little function sends the WM_GETTEXT message to the window and returns the window text (in this case, the text in the omnibox).
There you go!
Christian's answer did not work for me as internal structure of Chrome changed entirely and you can't really access elements of Chrome window using win32gui anymore.
The only possible way I managed to find was through UI Automation API, which has this python wrapper with some examples of usage
Run this and switch to Chrome window you want to grab address from:
from time import sleep
import uiautomation as automation
if __name__ == '__main__':
sleep(3)
control = automation.GetFocusedControl()
controlList = []
while control:
controlList.insert(0, control)
control = control.GetParentControl()
if len(controlList) == 1:
control = controlList[0]
else:
control = controlList[1]
address_control = automation.FindControl(control, lambda c, d: isinstance(c, automation.EditControl) and "Address and search bar" in c.Name)
print address_control.CurrentValue()
I quite new to StackOverFlow so apologies if the comment is out of tone.
After looking at :
Selenium,
launching chrome://History directly,
doing some keyboard emulation : copy/paste with Pywinauto,
trying to use SOCK_RAW connections to capture the headers as per the Network tab of the DevTool (this one was very interesting),
trying to get text of the omnibus/searchBar window element,
closing and reopening chrome to read the history tables,
....
I resulted in copy/pasting the History file itself (\AppData\Local\Google\Chrome\User Data\Default\History) into my application folder when the title of the window (retrieved using the hwnd + win32) is missing from "my" urls table.
This can be done even if the sqlite db is locked and does not interfere with the user experience.
Very basic solution that requires : sqlite3, psutil, win32gui.
Hope that helps.
How can my Python script get the URL of the currently active Google Chrome tab in Windows? This has to be done without interrupting the user, so sending key strokes to copy/paste is not an option.
First, you need to download and install pywin32. Import these modules in your script:
import win32gui
import win32con
If Google Chrome is the currently active window, first get the window handle by:
hwnd = win32gui.GetForegroundWindow()
(Otherwise, find the Google Chrome window handle by using win32gui.FindWindow. Windows Detective is handy when finding out class names for windows.)
It seems the only way to get the URL is to get the text in the "omnibox" (address bar). This is usually the tab's URL, but could also be any partial URL or search string that the user is currently typing.
Also, the URL in the omnibox won't include the "http://" prefix unless the user has typed it explicitly (and not yet pressed enter), but it will in fact include "https://" or "ftp://" if those protocols are used.
So, we find the omnibox child window inside the current Chrome window:
omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)
This will of course break if the Google Chrome team decides to rename their window classes.
And then we get the "window text" of the omnibox, which doesn't seem to work with win32gui.GetWindowText for me. Good thing there's an alternative that does work:
def getWindowText(hwnd):
buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buf = win32gui.PyMakeBuffer(buf_size)
win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf)
return str(buf)
This little function sends the WM_GETTEXT message to the window and returns the window text (in this case, the text in the omnibox).
There you go!
Christian's answer did not work for me as internal structure of Chrome changed entirely and you can't really access elements of Chrome window using win32gui anymore.
The only possible way I managed to find was through UI Automation API, which has this python wrapper with some examples of usage
Run this and switch to Chrome window you want to grab address from:
from time import sleep
import uiautomation as automation
if __name__ == '__main__':
sleep(3)
control = automation.GetFocusedControl()
controlList = []
while control:
controlList.insert(0, control)
control = control.GetParentControl()
if len(controlList) == 1:
control = controlList[0]
else:
control = controlList[1]
address_control = automation.FindControl(control, lambda c, d: isinstance(c, automation.EditControl) and "Address and search bar" in c.Name)
print address_control.CurrentValue()
I quite new to StackOverFlow so apologies if the comment is out of tone.
After looking at :
Selenium,
launching chrome://History directly,
doing some keyboard emulation : copy/paste with Pywinauto,
trying to use SOCK_RAW connections to capture the headers as per the Network tab of the DevTool (this one was very interesting),
trying to get text of the omnibus/searchBar window element,
closing and reopening chrome to read the history tables,
....
I resulted in copy/pasting the History file itself (\AppData\Local\Google\Chrome\User Data\Default\History) into my application folder when the title of the window (retrieved using the hwnd + win32) is missing from "my" urls table.
This can be done even if the sqlite db is locked and does not interfere with the user experience.
Very basic solution that requires : sqlite3, psutil, win32gui.
Hope that helps.