I want to open google chrome browser and go to facebook and terminate the python program but keep the google chrome window open until I manually close it. Please give me your own idea/Program with the above said as the aim.
I expect the chrome window to remain open after the program terminates, but it closes automatically after the program terminates.
Using os.system() should be avoided because it is platform dependent and because it isn't secure: if you use os.system('start chrome "%s"') % url where url is a string submitted by the user, someone can enter www.facebook.com" && shutdown /s /t "0 Facebook will open in a new Chrome window but then the computer will shut down.
The easiest way to open a new page in the browser is:
import webbrowser
webbrowser.open_new("www.facebook.com")
It remains open when the Python script terminates.
Try this, works on windows!
import os
os.system("start chrome \"www.facebook.com\"")
This shall open a chrome browser with the Facebook URL using cmd and it remains open even after the termination of the program.
Related
I am running a Flask server and I have the following problem.
When an user login in, a Selenium webdriver is initialized and performs some task. It store some cookies and then it communicates with frontend (I can't control WHEN it will save the cookies and I cannot close it with driver.close(). After this I need to start again the chromedriver but preserving the cookies (I'm using User dir for this reason and this works).
The problem is that the second time I start the webdriver I get error because the previous one is not closed. How can I close it before starting a new one, using Python?
Thanks!
I expect to close all the active chromedriver sessions without using Selenium (I cannot use it), but using Python.
Ideally, you want to driver.quit() to gracefully close all browser windows (note that driver.close() only closes the window in focus). If that's not possible, you can use psutil to kill the chromedriver processes:
for proc in psutil.process_iter():
if 'chromedriver' in proc.name():
proc.kill()
A similar approach can work with the built-in subprocess, but maybe with a few extra steps depending on your OS.
You can save the cookies ina txt file, and every time you run the drive, you add the cookies with 'driver.get_cookies()', 'drive.add_cookie()' and these structure:
content_cookies = {
'name': <NAME_VARIABLE_COOKIE>,
'domain': '<URLSITE>',
'value': str(<VALUE_VARIABLE_COOKIE>)
}
driver.add_cookie(content_cookies)
I have a setup where I create a Remote driver (with Chromedriver), go to a website, perform actions on it. I'm running the driver with headless=False, so Selenium creates a Chrome window.
When I have the Chrome window open and in foreground, everything works just fine.
When I have it reduced to icon, or even open but in background - so using other apps when Selenium is working -, then the driver can stall - but it will, like 80% of the times.
When this happens, I have to reopen the Chrome window and, if this fails to resume the execution, I have to go to the running script's terminal and press Enter - so send an event to the script -; usually this solves the stall, and the execution will continue.
I know that, when running with headless=True, this problem doesn't show up; however I cannot use it, since the website in question will change the page according to this setting, so my currently situation is running this script with this Chrome window in front of me.
The script execution will last from 5 to 10 minutes everytime it's runned, if this can may be related to the problem.
Is there anything I can do to mitigate, or even remove this problem at all?
I am writing an application where I am checking for a condition to be true every second. If the condition is true, a specific url needs to get opened in Chrome but only if that URL isn't already opened in chrome. Otherwise if the condition is true, every second a new tab will be opened. How do I check that? I know below code is used to check if chrome is running but how do I check which URL is running in Chrome?
import psutil as psutil
for proc in psutil.process_iter():
proc_name = proc.name()
if proc_name == 'chrome.exe':
print('chrome is running now.')
# open your program in this position
else:
print(proc_name)
My current code is below:
def workflow_chilled_water_trigger():
threading.Timer(1.0, workflow_chilled_water_trigger).start()
flow=float(flow_main_chiller())
supply_temp=float(inlet_temp_main_chiller())
return_temp=float(outlet_temp_main_chiller())
if ((flow > 0) or ((return_temp-supply_temp)<5)):
os.system('start chrome "https://www.youtube.com"')
workflow_chilled_water_trigger()
Unless you're using selenium or any similar solution to run the web browser first of all, then you'll have a hard time getting into the chrome window then getting the address bar and perform any other actions
I'd suggest either using selenium or similar tools and launch the web browser from there, then you'll have more control over the actions, address bar etc.
If it doesn't fits your needs it probably would be easier to create a chrome extension instead.
Using Python webbrowser package I can open a new tab with a specified URL. Is there a way to close this tab? I referred the below official docs and nothing related to close action is mentioned.
Python webbrowser package doc: https://docs.python.org/3/library/webbrowser.html
You can use pyautogui to close the browser tab when your task is fulfilled.
import time,webbrowser, pyautogui
def open_close(url="https://www.python.org/"):
webbrowser.open(url)
time.sleep(20)
pyautogui.hotkey('ctrl', 'w')
print("tab closed")
No, webbrowser doesn't have methods to close tabs nor browser itself as you may see in its documentation page:
https://docs.python.org/2/library/webbrowser.html
You could
Use a hotkey using the pykeyboard library which you can read about at https://github.com/SavinaRoja/PyUserInput
or the keyboard library at https://github.com/boppreh/keyboard
Another (but probably worse) option is:
You may use a "taskkill" command like
import os
os.system("taskkill /im chrome.exe /f")
However, this will just kill all processes and close the chosen program (in this case chrome.exe)
(This also may delete data from the browser, f.eks. you lose all you're windows even tho you have chosen in settings to save them for next time you open your browser)
u can close the tab by driver.close if u are using selenium package
I've set up a portable environment on my flash drive consisting of Chromium Portable, Firefox Portable and Python 3. I am trying to write a Python 3 script that will launch a pydoc server to be accessed either in Chromium Portable or Firefox Portable. If Chromium Portable is already active, a new tab to the server will be opened, if not Firefox Portable will be launched and the server will be accessed from there. When all processes of Chromium Portable\chrome.exe and Firefox Portable have been closed, the server should be shut down. The following code is what I have written so far.
import subprocess
import os
drive = os.environ['HOMEDRIVE']
def launch_browser():
pass
def launch_pydoc():
pythonw = drive + '\PortableApps\PortablePython_3x\App\pythonw.exe'
doc_args = drive + '\PortableApps\PortablePython_3x\App\Lib\pydoc.py -p 50000'
spDoc = subprocess.Popen(pythonw+' '+doc_args)
def launch_chrome():
chrome = drive + '\PortableApps\ChromiumPortable\App\Chrome-bin\chrome.exe'
chrome_args = r'http://localhost:50000/ --user-data-dir="C:\Users\Owner\AppData\Roaming\ChromePortable\nathan" --new-tab'
spChrome = subprocess.Popen(chrome+' '+chrome_args)
def launch_mozilla():
mozilla = drive + '\PortableApps\FirefoxPortableNightly\FirefoxPortable.exe'
mozilla_args = 'http://localhost:50000/'
spMozilla = subprocess.Popen(mozilla+' '+mozilla_args)
This script is launched from a batch file that sets the value of HOMEDRIVE to the current flash drive letter so Python will always know where to look for the executables. My problem is that I'm not sure how to implement the process that will determine whether to simply open a new tab in Chromium Portable or to open Firefox Portable and furthermore to shut down the server after each process of whichever browser has been closed. I have looked at many links pertaining to subprocess etc especially how to wait for multiple child processes, how to kill a subprocess and ensuring subprocesses are dead on exiting python program. I have installed pywin32, wmi, comtypes and psutil packages in my copy of Python 3. Help please? If it is necessary for my code to be discarded it is OK. I am trying to learn. Thanks in advance.
In principle, you should be able to use the wait() method of your Popen objects. Something like this:
pydoc_process = launch_pydoc()
browser_process = launch_browser()
browser_process.wait()
pydoc_process.terminate()
(Modify your launch functions to end with return subprocess.Popen(...)
But I don't know how well that will work with modern browsers. In Linux, if Firefox is called to open an address, and it detects you've already got Firefox open, the new process hands the URL to the old process, and exits immediately. That sort of thing would mess up what you're trying to do.