Selenium Browser window not quitting - python-3.x

here is my code so far:
from selenium import webdriver
import time
option = webdriver.ChromeOptions()
option.binary_location = 'C:\Program Files (x86)\AVG\Browser\Application\AVGBrowser.exe'
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\AVG\Browser\Application\AVGBrowser.exe', options=option)
driver.get("https://www.google.com")
time.sleep(3)
driver.quit() # What im trying to fix
The new browser window opens but does not quit after 3 seconds. It just gives me the error:
C:\Users\Tomas\PycharmProjects\AutoSpotify\venv\Scripts\python.exe C:/Users/Tomas/PycharmProjects/AutoSpotify/venv/Scripts/StartSpotify.py
Traceback (most recent call last):
File "C:/Users/Tomas/PycharmProjects/AutoSpotify/venv/Scripts/StartSpotify.py", line 4, in <module>
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\AVG\Browser\Application\AVGBrowser.exe')
File "C:\Users\Tomas\PycharmProjects\AutoSpotify\venv\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
self.service.start()
File "C:\Users\Tomas\PycharmProjects\AutoSpotify\venv\lib\site-packages\selenium\webdriver\common\service.py", line 98, in start
self.assert_process_still_running()
File "C:\Users\Tomas\PycharmProjects\AutoSpotify\venv\lib\site-packages\selenium\webdriver\common\service.py", line 111, in assert_process_still_running
% (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service C:\Program Files (x86)\AVG\Browser\Application\AVGBrowser.exe unexpectedly exited. Status code was: 0
Process finished with exit code 1

Hay i just tested the code in my linux it& looks fine :
Try this :
# Optional argument : if not specified WebDriver will search your system PATH environment variable for locating the chromedriver
For windows:
# try to place your driver within (Downloads) for example, no need to place it inside programe file or somewhere far.
driver = webdriver.Chrome("C:\\Users\\username\\Downloads\\chromedriver")

You should call your quit in a finally like so:
...
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\AVG\Browser\Application\AVGBrowser.exe', options=option)
try:
driver.get("https://www.google.com")
...
finally:
driver.quit()
This way, the quit function is called even if you encounter an exception while working with your driver object.

Related

Getting this ONNXRuntimeError again and again. Please suggest

I am trying to run this code to remove background from my image but I keep getting an error. Please tell me what I am doing wrong
from rembg.bg import remove
import numpy as np
import io
from PIL import Image
input_path = 'crop.jpeg'
output_path = 'out.png'
f = np.fromfile(input_path)
result = remove(f)
img = Image.open(io.BytesIO(result)).convert("RGBA")
img.save(output_path)
*C:\Sauhard\Internships\TEST IMAGES>python -u "c:\Sauhard\Internships\TEST IMAGES\a.py"
Traceback (most recent call last):
File "c:\Sauhard\Internships\TEST IMAGES\a.py", line 10, in <module>
result = remove(f)
File "C:\Users\Sauhard Saini\AppData\Local\Programs\Python\Python39\lib\site-packages\rembg\bg.py", line 133, in remove
session = new_session("u2net")
File "C:\Users\Sauhard Saini\AppData\Local\Programs\Python\Python39\lib\site-packages\rembg\session_factory.py", line 60, in new_session
ort.InferenceSession(
File "C:\Users\Sauhard Saini\AppData\Local\Programs\Python\Python39\lib\site-packages\onnxruntime\capi\onnxruntime_inference_collection.py", line 347, in __init__
self._create_inference_session(providers, provider_options, disabled_optimizers)
File "C:\Users\Sauhard Saini\AppData\Local\Programs\Python\Python39\lib\site-packages\onnxruntime\capi\onnxruntime_inference_collection.py", line 395, in _create_inference_session
sess.initialize_session(providers, provider_options, disabled_optimizers)
RuntimeError: D:\a\_work\1\s\onnxruntime\core\session\provider_bridge_ort.cc:1029 onnxruntime::ProviderLibrary::Get [ONNXRuntimeError] : 1 : FAIL : LoadLibrary failed with error 126 "" when trying to load "C:\Users\Sauhard Saini\AppData\Local\Programs\Python\Python39\lib\site-packages\onnxruntime\capi\onnxruntime_providers_tensorrt.dll"*
This error is related to the generic graphics card driver provided with the Windows installation and happens mainly with AMD/ATI based solutions.
download and install the latest available version of the graphics card driver for your hardware at www.amd.com
Another option can be the installation of the "Visual C++ Redistributable Packages for Visual Studio".

AttributeError: 'NoneType' object has no attribute 'languages'

Goal : 1.Select PDF 2.OCR PDF 3.Write tabels to excel with onefile .exe
Script is working in Pycharm perfect but after compiling to exe i am getting this traceback.
Traceback (most recent call last):
File "OCR_Menu.py", line 26, in <module>
File "ocrmypdf\api.py", line 340, in ocr
File "ocrmypdf\_validation.py", line 240, in check_options
AttributeError: 'NoneType' object has no attribute 'languages'
[11220] Failed to execute script 'OCR_Menu' due to unhandled exception!
Any help to get this script working as a single executable file will be very appreciated!
Thank you!
import ocrmypdf
import camelot
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)
# if filename is not None:
if __name__ == '__main__': # To ensure correct behavior on Windows and macOS
ocrmypdf.ocr (filename, 'output.pdf', deskew=True,)
file = "output.pdf"
tables = camelot.read_pdf(file, pages = "1-end", flavor='stream')
print(tables.n)
tables=camelot.read_pdf(file, pages='1-end', flavor='stream')
tables.export(filename + ".xlsx", f='excel')
if you're currently using googletrans==3.0.0, please switch to googletrans==3.1.0a0 for the temporary fix.

sys.exit in python gives a SystemExit error pystray

I am running a PYSTRAY icon which starts a console program. When I try stopping it with this code
def stop_rtd():
print("Stopping RTD")
sys.exit()
icon.stop()
The system throws back this error
An error occurred when calling message handler
Traceback (most recent call last):
File "C:\Users\ramac\AppData\Local\Programs\Python\Python37\lib\site-packages\pystray\_win32.py", line 389, in _dispatcher
uMsg, lambda w, l: 0)(wParam, lParam) or 0)
File "C:\Users\ramac\AppData\Local\Programs\Python\Python37\lib\site-packages\pystray\_win32.py", line 209, in _on_notify
descriptors[index - 1](self)
File "C:\Users\ramac\AppData\Local\Programs\Python\Python37\lib\site-packages\pystray\_base.py", line 267, in inner
callback(self)
File "C:\Users\ramac\AppData\Local\Programs\Python\Python37\lib\site-packages\pystray\_base.py", line 368, in __call__
return self._action(icon, self)
File "C:\Users\ramac\AppData\Local\Programs\Python\Python37\lib\site-packages\pystray\_base.py", line 463, in wrapper0
return action()
File "C:/Tej/GitHub/Python/YahooDLs/try_systray.py", line 16, in stop_rtd
sys.exit()
SystemExit
RTD is the console program which is perpetual. It stops but the icon continues and console does not close. On closing the console the program exits and the icon is closed.
I am running this on Windows10
Please help me solve this problem.
I found an alternative way to exit the program. The os module also has a exit function called _exit. It takes one argument that is the exit code/status code. Usually it should be 0. So your function will look like this:
import os
def stop_rtd():
icon.stop()
os._exit(0)
Also note that you have to stop icon before exit the program.

'NoneType' object has no attribute 'open_session

i wrote a script to connect to sftp server in python but it showing this error below and i do not understand it. please help me fix the bug
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host="127.0.0.1", username="new34",password="password",cnopts=cnopts) as srv:
print("connection successful")
# Get the directory and file listing
data = srv.listdir()
srv.put("testfile.txt")
# Closes the connection
srv.close()
# Prints out the directories and files, line by line
for i in data:
print(i)
it shows the following error; please help to fix the bug
C:\Users\Rohan\PycharmProjects\untitled1\venv\Scripts\python.exe C:/Users/Rohan/PycharmProjects/untitled1/yu.py
C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\pysftp\__init__.py:61: UserWarning: Failed to load HostKeys from C:\Users\Rohan\.ssh\known_hosts. You will need to explicitly load HostKeys (cnopts.hostkeys.load(filename)) or disableHostKey checking (cnopts.hostkeys = None).
warnings.warn(wmsg, UserWarning)
Traceback (most recent call last):
connection successful
File "C:/Users/Rohan/PycharmProjects/untitled1/yu.py", line 10, in <module>
data = srv.listdir()
File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\pysftp\__init__.py", line 591, in listdir
self._sftp_connect()
File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\pysftp\__init__.py", line 205, in _sftp_connect
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\paramiko\sftp_client.py", line 164, in from_transport
chan = t.open_session(
AttributeError: 'NoneType' object has no attribute 'open_session'
Process finished with exit code 1
Your code has indentation issue.
Try this,
with pysftp.Connection(host="127.0.0.1", username="new34",password="password",cnopts=cnopts) as srv:
print("connection successful")
# Get the directory and file listing
data = srv.listdir()
srv.put("testfile.txt")
with automatically closes the connection. No need to close explicitly.

Error while executing javascript code in python3 while using selenium

I was trying to remove the ad and other pop-up using selenium after opening the webpage. The pop-up is getting removed but the ad is not getting removed. There is some error in executing javascript code(using it remove ad). For which there is no reason given. Also, for the ad, when I open the webpage myself by typing the link then ad does not appear but when I run the program, in code generated browser ad appears(reason I don't know). I have attached both code and error. Here is the code
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("http://indianexpress.com/columnists/")
// To remove pop-up
later = driver.find_elements(By.CLASS_NAME, "iz_block_button")
later[0].click()
//to remove ad
all_iframes = driver.find_elements_by_tag_name("iframe")
if len(all_iframes) > 0:
print("Ad Found\n")
driver.execute_script("""
var elems = document.getElementsByTagName('iframe');
for(var i = 0, max = elems.length; i < max; i++)
{
elems[i].visibility=hidden;
}
""")
print('Total Ads: ' + str(len(all_iframes)))
else:
print('No frames found')
driver.close()
Error:-
Traceback (most recent call last):
File "/Users/arjungoyal/Desktop/untitled/a.py", line 23, in <module>
""")
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 627, in execute_script
'args': converted_args})['value']
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: hidden is not defined
(Session info: chrome=66.0.3359.181)
(Driver info: chromedriver=2.38.552518 (183d19265345f54ce39cbb94cf81ba5f15905011),platform=Mac OS X 10.13.4 x86_64)
Please someone tell what the error is and how to remove it.

Resources