- If the search term returns multiple pages with similar or related content, the Wikipedia module may raise a DisambiguationError exception. In this case, you can catch the exception and use the options provided in the exception to determine which page to retrieve.
- Here's an example of how you can catch the DisambiguationError exception and select the best page from the options:
- import wikipedia
- try:
- # Search for pages that match the search term
- results = wikipedia.search("search term")
- # Get the best page from the search results
- page = wikipedia.page(results[0])
- except wikipedia.DisambiguationError as e:
- # Print the options provided in the exception
- print("Multiple pages were found with the search term:")
- print(e.options)
- # Prompt the user to select the best page
- selection = input("Please select the best page: ")
- # Get the page for the selected option
- page = wikipedia.page(selection)
- # Print the page's title and summary
- print(page.title)
- print(page.summary)
- This code will search for pages that match the search term, and if multiple pages are found, it will catch the DisambiguationError exception and print the options provided in the exception. The user can then select the best page from the options, and the code will retrieve the selected page and print its title and summary.
- You can also use the options provided in the DisambiguationError exception to automatically select the best page, rather than prompting the user to make a selection. For example, you could use a simple heuristic to select the page with the shortest title or the page with the most related terms to the search term.
- Watch: Exception handling tips in Python - Write better Python code:
Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.
Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license