win 10 toast notification with an image in python - python

Is there a way to create an interactive toast notification in windows 10 using python?
Currently I am using plyer and sometimes I use win10toast.
When someone clicks it i want it to open a page in the web browser and contain an image, icon, text, and user input

For the Image part, You can use the module winrt like this:
import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom
nManager = notifications.ToastNotificationManager
notifier = nManager.create_toast_notifier(r"C:\Users\Admin\AppData\Local\Programs\Python\Python38\python.exe")
tString = """
<toast>
<visual>
<binding template='ToastGeneric'>
<text>Another Message from Tim!</text>
<text>Hi there!</text>
<image placement="appLogoOverride" hint-crop="circle" src="https://picsum.photos/48?image=883"/>
</binding>
</visual>
</toast>
"""
xDoc = dom.XmlDocument()
xDoc.load_xml(tString)
notification = notifications.ToastNotification(xDoc)
#display notification
notifier.show(notification)
Also, There three places where you can put an image: AppLogoOverride, Inline and Hero.

I rummaged through the source code for win10toast and found they use this library for creating windows gui elements and here is the most recent release. There you should be able to find the right module to use

Related

PywinAuto - Excel Automation Can not click the button

I m making an Excel automation via pywinauto library. But there is a hard challange for me due to using Excel Oracle add-ins called Smartview.
I need to click 'Private Connections' button, however i can't find any little info in app.Excel.print_control_identifiers() Private Connections
So i tried to use inspector.exe for find ui element regarding private connections button, however i couldn't find any little solvetion inside of inspector.exe's result inspector's result
Then i used another program called UISpy, however i can only find private connection's pane inside of the program. UISpy's result
i tried to find an answer but i couldn't find out anything. So, can you help me to click here?
By the way here is my code :
import pywinauto
from pywinauto import application
from pywinauto.keyboard import send_keys
from pywinauto.controls.common_controls import TreeViewWrapper
program_path = r"C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE"
file_path = r"C:\Users\AytugMeteBeder\Desktop\deneme.xlsx"
app = application.Application(backend="uia").start(r'{} "{}"'.format(program_path, file_path))
# sapp = application.Application(backend="uia").connect(title = 'deneme.xlsx - Excel')
time.sleep(7)
myExcel = app.denemeExcel.child_window(title="Smart View", control_type="TabItem").wrapper_object()
myExcel.click_input()
Panel = app.denemeExcel.child_window(title="Panel", control_type="Button").wrapper_object()
Panel.click_input()
time.sleep(1)
app.denemeExcel.print_control_identifiers()

notification pops up without image python winrt

I was trying to send a notification with an image after a bit of googling I found this code in stack overflow
even though the code below gives a notification with space for the image, the image doesn't load
What I have tried
I tried adding time.sleep() between few lines to give it some time to load the image
tried changing the interpreter to python 3.9
tried changing image source to another image
executing the code from another computer
none of these worked
import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom
import time
app = r'C:\Users\Sandramohan\AppData\Local\Programs\Python\Python38\python.exe'
nManager = notifications.ToastNotificationManager
notifier = nManager.create_toast_notifier(app)
tString = """
<toast>
<visual>
<binding template='ToastGeneric'>
<text>Another Message from Tim!</text>
<text>Hi there!</text>
<image placement="appLogoOverride" HintCrop="circle" src="https://www.decotaime.fr/decoration/images/178/Tableau-design-plexi-Pixel-Art-Marylin-Blue-50x50_L26640.jpg"/>
</binding>
</visual>
</toast>
"""
xDoc = dom.XmlDocument()
time.sleep(5)
xDoc.load_xml(tString)
notification = notifications.ToastNotification(xDoc)
#display notification
notifier.show(notification)
I tried using some local image from my computer as src and it worked.
If it is not required for the image source to be online, simply download it and use it locally.
tString = """
<toast>
<visual>
<binding template='ToastGeneric'>
<text>Another Message from Tim!</text>
<text>Hi there!</text>
<image placement="appLogoOverride" HintCrop="circle" src="C:/.../main.ico"/>
</binding>
</visual>
</toast>
"""
Result
After running the code, I got this result:
I used random .ico from my PC just for test.

Python - Downloading PDF and saving to disk using Selenium

I'm creating an application that downloads PDF's from a website and saves them to disk. I understand the Requests module is capable of this but is not capable of handling the logic behind the download (File size, progress, time remaining etc.).
I've created the program using selenium thus far and would like to eventually incorporate this into a GUI Tkinter app eventually.
What would be the best way to handle the downloading, tracking and eventually creating a progress bar?
This is my code so far:
from selenium import webdriver
from time import sleep
import requests
import secrets
class manual_grabber():
""" A class creating a manual downloader for the Roger Technology website """
def __init__(self):
""" Initialize attributes of manual grabber """
self.driver = webdriver.Chrome('\\Users\\Joel\\Desktop\\Python\\manual_grabber\\chromedriver.exe')
def login(self):
""" Function controlling the login logic """
self.driver.get('https://rogertechnology.it/en/b2b')
sleep(1)
# Locate elements and enter login details
user_in = self.driver.find_element_by_xpath('/html/body/div[2]/form/input[6]')
user_in.send_keys(secrets.username)
pass_in = self.driver.find_element_by_xpath('/html/body/div[2]/form/input[7]')
pass_in.send_keys(secrets.password)
enter_button = self.driver.find_element_by_xpath('/html/body/div[2]/form/div/input')
enter_button.click()
# Click Self Service Area button
self_service_button = self.driver.find_element_by_xpath('//*[#id="bs-example-navbar-collapse-1"]/ul/li[1]/a')
self_service_button.click()
def download_file(self):
"""Access file tree and navigate to PDF's and download"""
# Wait for all elements to load
sleep(3)
# Find and switch to iFrame
frame = self.driver.find_element_by_xpath('//*[#id="siteOutFrame"]/iframe')
self.driver.switch_to.frame(frame)
# Find and click tech manuals button
tech_manuals_button = self.driver.find_element_by_xpath('//*[#id="fileTree_1"]/ul/li/ul/li[6]/a')
tech_manuals_button.click()
bot = manual_grabber()
bot.login()
bot.download_file()
So in summary, I'd like to make this code download PDF's on a website, store them in a specific directory (named after it's parent folder in the JQuery File Tree) and keep tracking of the progress (file size, time remaining etc.)
Here is the DOM:
I hope this is enough information. Any more required please let me know.
I would recommend using tqdm and the request module for this.
Here is a sample code that effectively achieves that hard job of downloading and updating progress bar.
from tqdm import tqdm
import requests
url = "http://www.ovh.net/files/10Mb.dat" #big file test
# Streaming, so we can iterate over the response.
response = requests.get(url, stream=True)
total_size_in_bytes= int(response.headers.get('content-length', 0))
block_size = 1024 #1 Kibibyte
progress_bar = tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True)
with open('test.dat', 'wb') as file:
for data in response.iter_content(block_size):
progress_bar.update(len(data)) #change this to your widget in tkinter
file.write(data)
progress_bar.close()
if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:
print("ERROR, something went wrong")
The block_size is your file-size and the time-remaining can be calculated with the number of iterations performed per second with respect to the block-size that remains. Here is an alternative - How to measure download speed and progress using requests?

Selenium python interact with FileOpen window

From Selenium, I managed to automate my tasks for a website.
However I ran into a problem:I need to upload a file to my web-page before submitting the form.
It is NOT an option to write the uploaded file into it's input element, because it is more complicated than this.
So basically I need to launch the FileUpload dialog by clicking a button, sendKeys there, and then close it by clicking on Ok.
I am wondering if this is even possible using just Selenium?
I am using it from python (so I don't have access to Robot class)
I tried so far:
element.click()
time.sleep(5)
alert = driver.switch_to.alert
alert.send_keys("path.to.myfile.txt")
alert.accept()
(nothing happens - I mean, the file open dialog works fine, but it does not send the keys )
I also tried:
alert = driver.switch_to.alert
buildu = ActionChains(driver).send_keys('path.to.my.file.txt')
buildu.perform()
(also not working)
Maybe I am looking at it wrong...
Maybe the alerts is not a good approach?
Do you have any idea?
I would prefere not having to use AUTOIT (for my own reasons)
So my goal is to click on a link element (DONE) then the link opens the File Upload open file dialog (DONE), then I need to be able to enter a text in the only textBox of the new window, and click on the Ok button
EDIT
This is the Open File dialog that shows up.
All I want to do is send the filename directly to the window (the textBox is focused when the dialog shows up, so no need to make more actions). After I send the keys (text) I need to be able to click on the Open button
You can create a Java program that will paste the filename and press the enter key. I had this same problem exactly. This is how I implemented:
package myaots_basic;
import java.io.*;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
public class trial {
public static void main(String[] args) throws AWTException {
System.out.println("HELLO WORLD");
StringSelection attach1 = new StringSelection ("C:\\My Office Documents\\Selinium projects\\Data\\attachment1.doc");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(attach1, null);
Robot rb1 = new Robot();
rb1.delay(3000);
rb1.keyPress(KeyEvent.VK_CONTROL);
rb1.keyPress(KeyEvent.VK_V);
rb1.keyRelease(KeyEvent.VK_V);
rb1.keyRelease(KeyEvent.VK_CONTROL);
rb1.delay(500);
rb1.keyPress(KeyEvent.VK_ENTER); // press Enter
rb1.keyRelease(KeyEvent.VK_ENTER);
}
}
Name it to trial.jar. Make this class a an executable.
Then in your python code just add a simple step:
import subprocess
subprocess.call("java -jar trial.jar", shell=True)
I don't know if this is restricted to windows 10 or works slightly different in other Windows versions but you can use the following code/idea.
Open the windows shell with win32com.client.Dispatch("WScript.Shell")
Send Tab keys to navigate through the open file dialog
Paste your absolute file path into the top of the dialog and also into the file selection text field and send enter key when
tab-navigating to the "open" button
Make a sleep of at least 1 second between each action.. otherwise Windows blocks this action.
import win32com.client as comclt
...
def handle_upload_file_dialog(self, file_path):
sleep = 1
windowsShell = comclt.Dispatch("WScript.Shell")
time.sleep(sleep)
windowsShell.SendKeys("{TAB}{TAB}{TAB}{TAB}{TAB}")
time.sleep(sleep)
windowsShell.SendKeys("{ENTER}")
time.sleep(sleep)
windowsShell.SendKeys(file_path)
time.sleep(sleep)
windowsShell.SendKeys("{TAB}{TAB}{TAB}{TAB}{TAB}")
time.sleep(sleep)
windowsShell.SendKeys(file_path)
time.sleep(sleep)
windowsShell.SendKeys("{TAB}{TAB}")
time.sleep(sleep)
windowsShell.SendKeys("{ENTER}")
...

Upload a file using WebDriver & PyWinAuto

I have a python script that tries to upload a file from my PC to a web application.
I press via WebDriver the specific upload button in the browser and then a Win7 explorer window opens for me to navigate and select the desired file to upload.
How could I manipulate this window with pywinauto?
optional: could this be done in linux as well (with an appropriate library I suppose) ?
This is my sample code:
wd.find_element_by_css_selector("img.editLecturesButtons.fromVideo").click()
#switch to the lightbox
wd.switch_to_frame(int("1"))
#hit upload
wd.find_element_by_xpath("//*[#id='fileUpload']").click()
#TODO
import os,pywinauto.application
file = os.path.normpath("C:\Users\me\Desktop\image.jpg")
....
I agree with Mark, you should try the Webdriver methods. Regard to pywinauto, code may looks like:
import pywinauto
pwa_app = pywinauto.application.Application()
w_handle = pywinauto.findwindows.find_windows(title=u'Open', class_name='#32770')[0]
window = pwa_app.window_(handle=w_handle)
ctrl = window['Name']
ctrl.SetText(file)
ctrl = window['OK']
ctrl.Click()
This sollution only for Windows, since pywinauto uses win32 api.

Categories