How to Extract URL from a String in Python

In this tutorial, we will program 'How to Extract URLs from a String in Python'. We will learn how to extract URLs from a string. The objective is to enable you to efficiently get only the URLs of websites from a string. I will provide a sample program to demonstrate the actual coding process in this tutorial.

This topic is very easy to understand. Just follow the instructions I provide, and you can do it yourself with ease. The program I will show you covers the basics of programming for extracting URLs from a string. I will do my best to provide you with a simple method for obtaining URLs. So, let's start with the coding.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. import re
  4. def Find(string):
  5. regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
  6. url = re.findall(regex, string)
  7. return [x[0] for x in url]
  10. ret = False
  13. while True:
  14. print("\n================== Extract URL from a String ==================\n\n")
  16. string = 'sourcecodester website:'
  18. print(string)
  20. print("Please visit sourcecodester: ", Find(string))
  24. opt = input("\nDo you want to try again?(yes/no): ")
  26. if opt.lower() == 'yes':
  27. ret=False
  28. elif opt.lower() == 'no':
  29. ret=True
  30. print("Exiting program....")
  32. else:
  33. print("Please enter yes/no:")
  34. break
  36. if ret == False:
  37. continue

This script identifies the second largest number in a predefined list. It first removes duplicate elements and sorts the list in ascending order. In an infinite loop, it displays the original list and prints the second largest number from the sorted list. The user is prompted to decide whether to repeat the operation or exit the program. If the user chooses to repeat, the loop continues; otherwise, the program exits.


The How to Extract URL from a String in Python source code that I provide can be download below. Please kindly click the download button.

There you have it we successfully created How to Extract URL from a String in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment