I want to perform following task 3 times without closing browser.
Open Google.com in a Tab.
Open New Tab
Then close tab containing Google.com
Open Google.com in previous newly opened tab.
I am using following code to open new tab:
browser.execute_script("window.open('', 'new_tab')")
But when executed in a loop it only gets executed once.
I have printed Number of Window Handles which suggests that execute_script is executed only once.
My Full Code:
cpath="C:/Users/Gupta Niwas/Downloads/Softwares/Browsers/Drivers/chromedriver_win32/chromedriver.exe"
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
chrome_options.add_argument("start-maximized")
#browser = webdriver.Firefox(executable_path=fpath)
browser = webdriver.Chrome(chrome_options=chrome_options,executable_path=cpath)
for i in range(3):
browser.get("https://google.com")
print(len(browser.window_handles))
print("current:",browser.current_window_handle)
browser.execute_script("window.open('', 'new_tab')")
print(len(browser.window_handles))
next_tab=browser.window_handles[len(browser.window_handles)-1]
print(next_tab)
print(browser.title)
browser.close()
print(len(browser.window_handles))
browser.switch_to_window(next_tab)
browser.delete_all_cookies()
On the 2nd loop it throws an Exception:
runfile('C:/Users/Gupta Niwas/Downloads/Programming/Projects/Mi/temp5.py',
wdir='C:/Users/Gupta Niwas/Downloads/Programming/Projects/Mi')
1
current: CDwindow-75E62D95A2A8A7808C5AC369A8070641
2
CDwindow-F1C8AFC0E5742A2E55CEA17FCD951D1D
Google
1
1
current: CDwindow-F1C8AFC0E5742A2E55CEA17FCD951D1D
1
CDwindow-F1C8AFC0E5742A2E55CEA17FCD951D1D
Google
Traceback (most recent call last):
File "<ipython-input-1-12046950abfa>", line 1, in <module>
runfile('C:/Users/Gupta Niwas/Downloads/Programming/Projects/Mi/temp5.py', wdir='C:/Users/Gupta Niwas/Downloads/Programming/Projects/Mi')
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Gupta Niwas/Downloads/Programming/Projects/Mi/temp5.py", line 34, in <module>
print(len(browser.window_handles))
File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 719, in window_handles
return self.execute(Command.GET_WINDOW_HANDLES)['value']
File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute
self.error_handler.check_response(response)
File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
WebDriverException: no such session
(Driver info: chromedriver=2.40.565498 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform=Windows NT 10.0.17134 x86_64)
I think here is a problem:
next_tab = browser.window_handles[len(browser.window_handles)-1]
Your next_tab is getting a current window reference. And when you are closing current window:
browser.close()
You cannot switch to next_tab, because it is not exists. I suggest you to debug your code and find out which value should you have in browser.window_handles[?]
Related
While the epub is being generated successfully, but when I try to read the epub using readers like Calibre or Sigil. They throw errors like certain files are missing.
Here's my code to generate the epub file:
book = epub.EpubBook()
book.set_title(novelName)
book.set_language("en")
book.set_cover('temp.jpg', content=open('temp.jpg','rb').read())
book.set_identifier("test")
for i in authorNames:
book.add_author(i)
for i in range(1):
driver.get(chapterLinks[i])
try:
content=driver.find_element_by_id('chr-content').get_attribute("innerHTML")
time.sleep(5)
except Exception as e:
driver.close()
driver = webdriver.Chrome(ChromeDriverManager().install(),options=options)
driver.get(chapterLinks[i])
content=driver.find_element_by_id('chr-content').get_attribute("innerHTML")
time.sleep(5)
soup = BeautifulSoup(content)
ads=soup.find("div", class_="ads-holder")
if(ads!=None):
ads.decompose()
print(chapterNames[i], chapterLinks[i])
chapterName=chapterNames[i].replace("-","")
c=epub.EpubHtml(title=chapterName,
file_name='{}.xhtml'.format(chapterName),
lang='en')
c.set_content(str(soup).encode('utf-8'))
book.add_item(c)
chapterList.append(c)
book.toc = chapterList
book.spine = chapterList
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
epub.write_epub('test.epub', book)
and here are the errors:
Calibre :
calibre, version 5.20.0
ERROR: Loading book failed: Failed to open the book at C:\Users\xxxxx\Documents\Visual Studio 2019\PersonalProjects\Novel Grabber\test.epub. Click "Show details" for more info.
Failed to convert book: C:\Users\xxxxx\Documents\Visual Studio 2019\PersonalProjects\Novel Grabber\test.epub with error:
InputFormatPlugin: EPUB Input running
on C:\Users\xxxxx\Documents\Visual Studio 2019\PersonalProjects\Novel Grabber\test.epub
Failed to run pipe worker with command: from calibre.srv.render_book import viewer_main; viewer_main()
Traceback (most recent call last):
File "runpy.py", line 194, in _run_module_as_main
File "runpy.py", line 87, in _run_code
File "site.py", line 82, in <module>
File "site.py", line 77, in main
File "site.py", line 49, in run_entry_point
File "calibre\utils\ipc\worker.py", line 197, in main
File "<string>", line 1, in <module>
File "calibre\srv\render_book.py", line 824, in viewer_main
File "calibre\srv\render_book.py", line 815, in render_for_viewer
File "calibre\srv\render_book.py", line 793, in render
File "calibre\srv\render_book.py", line 601, in process_exploded_book
File "calibre\srv\render_book.py", line 604, in <setcomp>
File "calibre\ebooks\oeb\polish\container.py", line 561, in has_name_and_is_not_empty
File "genericpath.py", line 50, in getsize
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\xxxxxx\\AppData\\Local\\calibre-cache\\ev2\\t\\c0-vdo66nim\\EPUB\\Chapter 2 '
Sigil:
Files exist in epub that are not listed in manifest, they will be ignored
Does anybody know what could be the cause for this?
Download chromedriver and extract it.
from selenium import webdriver
driver = webdriver.Chrome(executable_path='/home/debian/Downloads/chromedriver')
It works fine.
Now to test geckodriver for firefox,my firefox version is 78.0.2 (64-bit),the latest version,i have downloaded the geckodriver-v0.26.0-linux64.tar.gz and extract it.
from selenium import webdriver
driver = webdriver.Firefox(executable_path='/home/debian/Downloads/geckodriver')
It encounter some issues:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/webdriver.py", line 174, in __init__
keep_alive=True)
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
self.start_session(capabilities, browser_profile)
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities
How to fix it?
first check if selenium are downloaded with no error and make sure that the webdriver are downloaded in the path in this code driver = webdriver.Firefox(executable_path='/home/debian/Downloads/geckodriver')
that's should fix your problem
Versions:
geckodriver 0.26.0 (in PATH environment variable)
selenium 3.141.0
Firefox 75.0
python 3.8.2
Windows 10
When I try:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://seleniumhq.org/')
I get this:
Traceback (most recent call last):
File "C:\Users\Me\Desktop\python\FFtests.py", line 3, in <module>
driver = webdriver.Firefox()
File "C:\Users\Me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 170, in __init__
RemoteWebDriver.__init__(
File "C:\Users\Me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in __init__
self.start_session(capabilities, browser_profile)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\Me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities
When I try:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
cap = DesiredCapabilities().FIREFOX
cap["marionette"] = False
driver = webdriver.Firefox(capabilities = cap)
driver.get('https://seleniumhq.org/')
I get this:
Traceback (most recent call last):
File "C:\Users\me\Desktop\python\FFtests.py", line 6, in <module>
driver = webdriver.Firefox(capabilities = cap)
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 190, in __init__
executor = ExtensionConnection("127.0.0.1", self.profile,
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\firefox\extension_connection.py", line 52, in __init__
self.binary.launch_browser(self.profile, timeout=timeout)
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 73, in launch_browser
self._wait_until_connectable(timeout=timeout)
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py", line 103, in _wait_until_connectable
raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.
IEDriver works fine for IE
I have Windows Visual Studio installed as https://github.com/mozilla/geckodriver/releases indicates I should.
What can I do to make this work?
This is likely an issue with FireFox version. Try updating Firefox and Selenium.
Update Firefox
Update Selenium
Reinstall/update Geckodriver
See here for more solutions.
i have this python script:
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome("/usr/bin/chromedriver", chrome_options=options)
driver.set_window_size(300, 500)
wait = WebDriverWait(driver, 30)
if i run it on my pc it will work just fine
the problem is when i use it on a vps, SOMETIMES it throws me this bunch of erros:
Traceback (most recent call last):
File "acad.py", line 31, in <module>
driver = webdriver.Chrome("/usr/bin/chromedriver", chrome_options=options)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/chrome/webdriver.py", line 75, in __init__
desired_capabilities=desired_capabilities)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__
self.start_session(desired_capabilities, browser_profile)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 310, in execute
response = self.command_executor.execute(driver_command, params)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/remote_connection.py", line 466, in execute
return self._request(command_info[0], url, body=data)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/remote_connection.py", line 490, in _request
resp = self._conn.getresponse()
File "/usr/lib/python3.6/http/client.py", line 1331, in getresponse
response.begin()
File "/usr/lib/python3.6/http/client.py", line 297, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.6/http/client.py", line 258, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer
i have chromedriver on /usr/bin and chrome is under /usr/bin/google-chrome-stable
any ideas????
A couple of things you might try.
I, personally, found that Firefox' geckogriver worked more reliable for me. I found others on the web reporting the same thing. Below is the script that I use for the geckodriver.
Also, as others have mentioned in the comments, memory management is critical with either driver. If your code throws an exception, the OS will not automatically destroy the resource (it treats is as an opened web browser). You have to be extremely careful to always exit with a driver.quit() statement. A great pattern is to use python's 'with' statement. The combination of the above made the problem go away for me.
[My connection script]
headless = True
options = webdriver.FirefoxOptions()
if "Linux" in platform.system():
path = "path/to/geckodriver"
else:
path = "path/to/geckodriver.exe")
if headless:
options.add_argument("-headless")
driver = webdriver.Firefox(executable_path=path, firefox_options=options)
driver.implicitly_wait(10)
I am running a code to connect Keithley multimeter to my laptop. I am using windows 10 and python 2.7. But when I try to run the code, this appears. Help me, i am very basic in programming and computer and I am in need of help. I have been searching for solution for days but to no avail , after I have fixed one error, another error pops up. this is the latest error. I hope after this one is solved i can use it . This is the message from iPython
runfile('C:/Users/user/Downloads/program (2).py',
wdir='C:/Users/user/Downloads') initializing Traceback (most recent
call last):
File "", line 1, in
runfile('C:/Users/user/Downloads/program (2).py', wdir='C:/Users/user/Downloads')
File
"C:\Users\user\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py",
line 710, in runfile
execfile(filename, namespace)
File
"C:\Users\user\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py",
line 86, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/user/Downloads/program (2).py", line 422, in
dmm = DMM()
File "C:/Users/user/Downloads/program (2).py", line 40, in init
self.A=self.rm.open_resource('ASRL3::INSTR')
File "C:\Users\user\Anaconda2\lib\pyvisa\highlevel.py", line 1656,
in open_resource
res.open(access_mode, open_timeout)
File "C:\Users\user\Anaconda2\lib\pyvisa\resources\resource.py",
line 209, in open
self.session, status = self._resource_manager.open_bare_resource(self._resource_name,
access_mode, open_timeout)
File "C:\Users\user\Anaconda2\lib\pyvisa\highlevel.py", line 1613,
in open_bare_resource
return self.visalib.open(self.session, resource_name, access_mode, open_timeout)
File "C:\Users\user\Anaconda2\lib\pyvisa\ctwrapper\functions.py",
line 1213, in open
ret = library.viOpen(session, resource_name, access_mode, open_timeout, byref(out_session))
File "C:\Users\user\Anaconda2\lib\pyvisa\ctwrapper\highlevel.py",
line 188, in _return_handler
raise errors.VisaIOError(ret_value)
VisaIOError: VI_ERROR_RSRC_NFOUND (-1073807343): Insufficient location
information or the requested device or resource is not present in the
system.