Search code examples
pythonwebweb-scrapingpyautogui

How to focus on a window with python?


I'm writing a python code that allows a user to mark text from a website and then paste it into a word document. I'm using pyautogui and win32clipboard.

So here is the flow- 1. the user finds an interesting line on a website. 2. the user marks the desired text. 3. the user runs the python script ( I don't want python to run all the time, only when asked). 4. python uses pyautogui to copy the text (ctrl + c) and then win32clipboard. 5. python writes the copied text to a doc file.

As for now, the only problem I have is in the transition from 3 to 4. The issues are-

a) when I try to run the python from cmd, ctrl c hotkey makes the script stop (keyboard interrupt). How can I overcome that?

b) how can I make the script run on the current website? how do I return the focus to that window? as for now, I'm running the script within Pycharm and it works, but I want it to run in the "outside world"!

Thanks in advance, Karin :-)

P.S- this is the code I'm trying to run.

--getting the url

pyautogui.hotkey("Ctrl","f")
time.sleep(.01)
pyautogui.hotkey("Ctrl","c")
time.sleep(.01)
win32clipboard.OpenClipboard()
url = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()

--- getting the marked text

pyautogui.hotkey("Ctrl","c")
time.sleep(.01)
win32clipboard.OpenClipboard()
text = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()


Solution

  • Well, after a lot of research, I found a very simple solution for the problem- using time.sleep(). During that time the user can switch to the desired window and the code works fine :-)