Solution 1 :

Here you are using session.close()
it will close only browser:

this is the backend code of close:

def close(self):
        """ If a browser was created close it first. """
        if hasattr(self, "_browser"):
            self.loop.run_until_complete(self._browser.close())
        super().close()

enter image description here

and you getting memmory object create at you can delete this object after close

from requests_html import HTMLSession

session_o = HTMLSession()


def hello():  # sourcery skip: raise-specific-error
    session = HTMLSession()
    print(session)
    raise Exception


try:
    hello()
except:
    print(session_o)
    session_o.close()
    print(session_o)
    del session_o
    print(session_o)

Solution 2 :

I think there are two potential questions here. One question is what happens if an exception is raised by the session object. That case is a bit interesting. But with your code, you’re not asking that question. You’re asking if raising and catching your own exception somehow affects the session object.

There’s no reason to expect that anything would happen to the session object because your code threw an exception. The exception has nothing to do with the session object. Rather, your code threw it for no reason at all. The session object never failed to do something, so from its point of view (and Python’s), session was created and is still ready to do whatever it does. An unrelated exception having been raised and caught does not impact the session object. Why would it?

Raising an exception is not fundamentally different than any other program flow control statement, like a while loop or an if/else. It’s a bit more complicated, but there’s nothing at all special about using it. Upon raise being called, the execution pointer is moved to another location (kinda like with a break in a while loop) and the exception that was raised is made available to the except code block. That’s it. There’s no behind the scene magic.

Problem :

from requests_html import HTMLSession

Does session closes automatically when an error occurs or do I need to close it by myself in the except bloc?

def hello():
    session = HTMLSession()
    raise Exception


try:
    hello()
except:
    session.close() # Do I need that?

Edit: I tried the following:

session = HTMLSession()
def hello():
    session = HTMLSession()
    print(session)
    raise Exception

try:
    hello()
except:
    print(session)
    session.close()
    print(session)

Output:

<requests_html.HTMLSession object at 0x107df59a0>
<requests_html.HTMLSession object at 0x1063dfcd0>
<requests_html.HTMLSession object at 0x1063dfcd0>

By