How can write this in a better way?

Question:

Do you have any idea to write this more cleanly ? I am using a module which have several function on it but the syntax is the same like you can see.

import browser_cookie3
site = "SOME WEBSITE"
cookies = []
try:
    cookies.append(str(browser_cookie3.chrome(domain_name=site)))
except:
    pass
try:
    cookies.append(str(browser_cookie3.edge(domain_name=site)))
except:
    pass
try:
    cookies.append(str(browser_cookie3.firefox(domain_name=site)))
except:
    pass
try:
    cookies.append(str(browser_cookie3.brave(domain_name=site)))
except:
    pass
try:
    cookies.append(str(browser_cookie3.opera(domain_name=site)))
except:
    pass
try:
    cookies.append(str(browser_cookie3.vivaldi(domain_name=site)))
except:
    pass
try:
    cookies.append(str(browser_cookie3.chromium(domain_name=site)))
except:
    pass
Asked By: Mouad Essalim

||

Answers:

If you create a list of the browser names as strings you can then use getattr to get the function from the module dynamically:

import browser_cookie3
site = "SOME WEBSITE"
cookies = []

browsers = [
    "chrome",
    "edge",
    "firefox",
    "brave",
    "opera",
    "vivaldi",
    "chromium",
]

for browser in browsers:
    try:
        cookies.append(str(getattr(browser_cookie3, browser)(domain_name=site)))
    except:
        pass

Note that you should specify the exact error to suppress: except AttributeError: for example. If you catch all errors like you are, it will make it difficult to debug later if there’s an unexpected error

Answered By: Mandera
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.