Search code examples
pythonparsingurlpython-re

Python: How to parse a Tiktok url from a given text


Hello I am trying to parse a text and extract the Tiktok Url that it is in it

text = "This is a text https://www.tiktok.com/@tt_user/video/7620173214578963251 and more text"

Normally in python, to parse an url, I use the following regex:

import re
url = re.search("(?P<url>https?://[^\s]+)", text).group("url")

But this method fails for tiktok (i assume it is for the "@" in the url)

AttributeError: 'NoneType' object has no attribute 'group'

I would like to know how to extract my tiktok urls properly by (1) using a regex or (2) Using another method


Solution

  • import re
    url = re.search("(?P<url>https?:\/\/[^\s]+)", text).group("url")
    

    You need to escape '\' the '/'