Getting started with Python LanguageList comprehensionsFilterListFunctionsDecoratorsMath ModuleLoopsRandom moduleComparisonsImporting modulesSorting, Minimum and MaximumOperator moduleVariable Scope and BindingBasic Input and OutputFiles & Folders I/OJSON ModuleString MethodsMetaclassesIndexing and SlicingGeneratorsSimple Mathematical OperatorsReduceMap FunctionExponentiationSearchingDictionaryClassesCountingManipulating XMLDate and TimeSetCollections moduleParallel computationMultithreadingWriting extensionsUnit TestingRegular Expressions (Regex)Bitwise OperatorsIncompatibilities moving from Python 2 to Python 3Virtual environmentsCopying dataTupleContext Managers (“with” Statement)Hidden FeaturesEnumString FormattingConditionalsComplex mathUnicode and bytesThe __name__ special variableChecking Path Existence and PermissionsPython NetworkingAsyncio ModuleThe Print Functionos.pathCreating Python packagesParsing Command Line argumentsHTML ParsingSubprocess Librarysetup.pyList slicing (selecting parts of lists)SocketsItertools ModuleRecursionBoolean OperatorsThe dis moduleType Hintspip: PyPI Package ManagerThe locale ModuleExceptionsWeb scraping with PythonDeque ModuleDistributionProperty ObjectsOverloadingDebuggingReading and Writing CSVDynamic code execution with `exec` and `eval`PyInstaller - Distributing Python CodeIterables and IteratorsData Visualization with PythonThe Interpreter (Command Line Console)*args and **kwargsFunctools ModuleGarbage CollectionIndentationSecurity and CryptographyPickle data serialisationurllibBinary DataPython and ExcelIdiomsMethod OverridingDifference between Module and PackageData SerializationPython concurrencyIntroduction to RabbitMQ using AMQPStormPostgreSQLDescriptorCommon PitfallsMultiprocessingtempfile NamedTemporaryFileWorking with ZIP archivesStackProfilingUser-Defined MethodsWorking around the Global Interpreter Lock (GIL)DeploymentLoggingProcesses and ThreadsThe os ModuleComments and DocumentationDatabase AccessPython HTTP ServerAlternatives to switch statement from other languagesList destructuring (aka packing and unpacking)Accessing Python source code and bytecodeMixinsAttribute AccessArcPyPython Anti-PatternsPlugin and Extension ClassesWebsocketsImmutable datatypes(int, float, str, tuple and frozensets)String representations of class instances: __str__ and __repr__ methodsArraysOperator PrecedencePolymorphismNon-official Python implementationsList ComprehensionsWeb Server Gateway Interface (WSGI)2to3 toolAbstract syntax treeAbstract Base Classes (abc)UnicodeSecure Shell Connection in PythonPython Serial Communication (pyserial)Neo4j and Cypher using Py2NeoBasic Curses with PythonPerformance optimizationTemplates in pythonPillowThe pass statementLinked List Nodepy.testDate FormattingHeapqtkinterCLI subcommands with precise help outputDefining functions with list argumentsSqlite3 ModulePython PersistenceTurtle GraphicsConnecting Python to SQL ServerDesign PatternsMultidimensional arraysAudioPygletQueue ModuleijsonWebbrowser ModuleThe base64 ModuleFlaskgroupby()Sockets And Message Encryption/Decryption Between Client and ServerpygameInput, Subset and Output External Data Files using Pandashashlibgetting start with GZipDjangoctypesCreating a Windows service using PythonPython Server Sent EventsMutable vs Immutable (and Hashable) in PythonPython speed of programconfigparserLinked listsCommonwealth ExceptionsOptical Character RecognitionPython Data TypesPartial functionspyautogui modulegraph-toolUnzipping FilesFunctional Programming in PythonPython Virtual Environment - virtualenvsysvirtual environment with virtualenvwrapperCreate virtual environment with virtualenvwrapper in windowsPython Requests PostPlotting with MatplotlibPython Lex-YaccChemPy - python packagepyaudioshelveUsage of "pip" module: PyPI Package ManagerIoT Programming with Python and Raspberry PICode blocks, execution frames, and namespaceskivy - Cross-platform Python Framework for NUI DevelopmentCall Python from C#Similarities in syntax, Differences in meaning: Python vs. JavaScriptWriting to CSV from String or ListRaise Custom Errors / ExceptionsUsing loops within functionsPandas Transform: Preform operations on groups and concatenate the results

Webbrowser Module

Other topics

Remarks:

The following table lists predefined browser types. The left column are names that can be passed into the webbrowser.get() method and the right column lists the class names for each browser type.

Type NameClass Name
'mozilla'Mozilla('mozilla')
'firefox'Mozilla('mozilla')
'netscape'Mozilla('netscape')
'galeon'Galeon('galeon')
'epiphany'Galeon('epiphany')
'skipstone'BackgroundBrowser('skipstone')
'kfmclient'Konqueror()
'konqueror'Konqueror()
'kfm'Konqueror()
'mosaic'BackgroundBrowser('mosaic')
'opera'Opera()
'grail'Grail()
'links'GenericBrowser('links')
'elinks'Elinks('elinks')
'lynx'GenericBrowser('lynx')
'w3m'GenericBrowser('w3m')
'windows-default'WindowsDefault
'macosx'MacOSX('default')
'safari'MacOSX('safari')
'google-chrome'Chrome('google-chrome')
'chrome'Chrome('chrome')
'chromium'Chromium('chromium')
'chromium-browser'Chromium('chromium-browser')

Opening a URL with Default Browser

To simply open a URL, use the webbrowser.open() method:

import webbrowser
webbrowser.open("http://stackoverflow.com")

If a browser window is currently open, the method will open a new tab at the specified URL. If no window is open, the method will open the operating system's default browser and navigate to the URL in the parameter. The open method supports the following parameters:

  • url - the URL to open in the web browser (string) [required]
  • new - 0 opens in existing tab, 1 opens new window, 2 opens new tab (integer) [default 0]
  • autoraise - if set to True, the window will be moved on top of other applications' windows (Boolean) [default False]

Note, the new and autoraise arguments rarely work as the majority of modern browsers refuse these commmands.

Webbrowser can also try to open URLs in new windows with the open_new method:

import webbrowser
webbrowser.open_new("http://stackoverflow.com")

This method is commonly ignored by modern browsers and the URL is usually opened in a new tab. Opening a new tab can be tried by the module using the open_new_tab method:

import webbrowser
webbrowser.open_new_tab("http://stackoverflow.com")

Opening a URL with Different Browsers

The webbrowser module also supports different browsers using the register() and get() methods. The get method is used to create a browser controller using a specific executable's path and the register method is used to attach these executables to preset browser types for future use, commonly when multiple browser types are used.

import webbrowser
ff_path = webbrowser.get("C:/Program Files/Mozilla Firefox/firefox.exe")
ff = webbrowser.get(ff_path)
ff.open("http://stackoverflow.com/")

Registering a browser type:

import webbrowser
ff_path = webbrowser.get("C:/Program Files/Mozilla Firefox/firefox.exe")
ff = webbrowser.get(ff_path)
webbrowser.register('firefox', None, ff)
# Now to refer to use Firefox in the future you can use this
webbrowser.get('firefox').open("https://stackoverflow.com/")

Syntax:

  • webbrowser.open(url, new=0, autoraise=False)
  • webbrowser.open_new(url)
  • webbrowser.open_new_tab(url)
  • webbrowser.get(usage=None)
  • webbrowser.register(name, constructor, instance=None)

Parameters:

ParameterDetails
webbrowser.open() 
urlthe URL to open in the web browser
new0 opens the URL in the existing tab, 1 opens in a new window, 2 opens in new tab
autoraiseif set to True, the window will be moved on top of the other windows
webbrowser.open_new() 
urlthe URL to open in the web browser
webbrowser.open_new_tab() 
urlthe URL to open in the web browser
webbrowser.get() 
usingthe browser to use
webbrowser.register() 
urlbrowser name
constructorpath to the executable browser (help)
instanceAn instance of a web browser returned from the webbrowser.get() method

Contributors

Topic Id: 8676

Example Ids: 27066,27067

This site is not affiliated with any of the contributors.