How to detect if a URL is open in Chrome? - python

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.

Related

Close all webdriver sessions using Python

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)

Keep the broweser open, after terminating the python program

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.

Python3, Selenium, Chromedriver console window

I've a made a selenium test using python3 and selenium library.
I've also used Tkinter to make a GUI to put some input on (account, password..).
I've managed to hide the console window for python by saving to the .pyw extension; and when I make an executable with my code, the console doesn't show up even if it's saved with .py extension.
However, everytime the chromedriver starts, it also starts a console window, and when the driver exists, this window does not.
so in a loop, i'm left with many webdriver consoles.
Is there a work around this to prevent the driver from launching a console everytime it runs ?
I hated dealing with this in selenium until I remembered that this was an obvious use case for context managers just like the usage of open.
I did find out that selenium is about to add this officially to their package in this pull request
Until this is officially added, this snippet should give you the functionality you need to get things going :)
import contextlib
#contextlib.contextmanager
def Chrome(*args, **kwargs):
webdriver = webdriver.Chrome(*args, **kwargs)
try:
yield webdriver
finally:
webdriver.quit()
with Chrome() as driver:
# whatever you're planning on doing goes here
driver.close() and driver.quit() are two different methods for closing the browser session in Selenium WebDriver.
driver.close() - It closes the the browser window on which the focus is set.
driver.quit() – It basically calls driver.dispose method which in turn closes all the browser windows and ends the WebDriver session gracefully.
You should use driver.quit whenever you want to end the program. It will close all opened browser window and terminates the WebDriver session. If you do not use driver.quit at the end of program, WebDriver session will not close properly and files would not be cleared off memory. This may result in memory leak errors.

Python Selenium send request and avoid "Waiting for (website) ...."

I am launching several requests on different tabs. While one tab loads I will iteratively go to other tabs and see whether they have loaded correctly. The mechanism works great except for one thing: a lot of time is wasted "Waiting for (website)..."
The way in which I go from one tab to the other is launching an exception whenever a key element that I have to find is missing. But, in order to check for this exception (and therefore to proceed on other tabs, as it should do) what happens is that I have to wait for the request to end (so for the message "Waiting for..." to disappear).
Would it be possible not to wait? That is, would it be possible to launch the request via browser.get(..) and then immediately change tab?
Yes you can do that. You need to change the pageLoadStrategy of the driver. Below is an example of firefox
import time
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium import webdriver
cap = DesiredCapabilities.FIREFOX
cap["pageLoadStrategy"] = "none"
print(DesiredCapabilities.FIREFOX)
driver = webdriver.Firefox(capabilities=cap)
driver.get("http://tarunlalwani.com")
#execute code for tab 2
#execute code for tab 3
Nothing will wait now and it is up to you to do all the waiting. You can also use eager instead of none

Selenium python (webdrivers): how to handle cases with multiple interconnected windows

I am looking for a way to track an app built on multiple interconnected windows.
Basically I have webdriver running happily, and launch the application which open a window; I can access its elements and everything is fine.
But there is another part of the application, that open on its own, which cause the main view to close. It is still the same application, but the main window is destroyed and the new one is created.
This cause sadly the issue that webdriver can't find the context anymore (because rightfully so, the app to which it was attached, has been destroyed).
content shell came up empty, the driver is Chromedriver 2.23.40 on OSX
Is there a way to handle such case with Selenium python webdriver?
Selenium has a switch_to method to control switching the active window.
# Get window handles
windows = driver.window_handles
print("Number of window handles: {0}".format(len(windows))
print("Current window handle: {0}".format(driver.current_window_handle)
# Switch that most recently opened one
driver.switch_to.window(windows[-1])
print("New window handle: {0}".format(driver.current_window_handle)

Categories