In Python, you often need to add links for various purposes, such as to point to a source of data, to refer to a documentation page, or to guide users to a webpage.
Python provides a simple library, called Hyperlink, which enables you to create, manipulate, and work with URLs in an intuitive way. In this tutorial, we will cover how to add a link in Python using the Hyperlink library.
Installation of Hyperlink Library
Before we begin, the first requirement is to install the Hyperlink library. If you haven’t installed it yet, you can easily install it via pip:
1 |
pip install hyperlink |
You can learn more about the Hyperlink library from its official document page.”
Creation of the Link
To create a link, you’ll first need to import the Hyperlink library. Python allows you to create a URL object. Let’s look at a simple example:
1 2 3 4 |
from hyperlink import URL url = URL(scheme='https', host='www.google.com') print(url.to_text()) |
In the above code snippet, we have created a URL object with the scheme ‘https’ and host ‘www.google.com’. The output of the above code will be:
1 |
https://www.google.com |
Adding Path and Query Parameters
You can also add path components and query parameters to a URL like the following:
1 2 |
url = URL(scheme='https', host='www.google.com', path=['search'], query=[('q', 'Python+programming')]) print(url.to_text()) |
The final result would output:
1 |
https://www.google.com/search?q=Python+programming |
By following these simple steps, you can easily add a link in Python.
The Full Code:
1 2 3 4 5 6 7 8 9 |
from hyperlink import URL # Creation of the Link url = URL(scheme='https', host='www.google.com') print(url.to_text()) # Adding Path and Query Parameters url = URL(scheme='https', host='www.google.com', path=['search'], query=[('q', 'Python+programming')]) print(url.to_text()) |
Conclusion
Adding a link in Python is an essential skill, especially for scraping web pages, API requests, etc. The Hyperlink library offers a highly readable, flexible, and chainable way to create, modify, and represent URLs in Python. The full version of the above script and other similar samples can be found in the Hyperlink library’s official documentation.
We encourage you to use this powerful tool for any tasks involving URLs and see the ease and readability it brings to your Python programming experience.