如何在Django中保存部分URL?

时间:2017-02-02 18:46:41

标签: python django

我想在save方法中保存部分URL,例如:

我有来自youtube的链接:

www.youtube.com/watch?v=wMXHHuEGuO8

但我只想保存这部分:wMXHHuEGuO8

我怎么能在Django中做到这一点?

2 个答案:

答案 0 :(得分:0)

这个答案特定于Python 3,并没有使用任何特定于Django的调用。您可以使用urllib.parse模块将URL解析为其部分:

import urllib.parse

url = 'www.youtube.com/watch?v=wMXHHuEGuO8'

query_string =  urllib.parse.urlparse(url).query
print(query_string)
# v=wMXHHuEGuO8

query_dict = urllib.parse.parse_qs(query_string)
print(query_dict)
# {'v': ['wMXHHuEGuO8']}

print(query_dict['v'])
# ['wMXHHuEGuO8']

print(query_dict['v'][0])
# wMXHHuEGuO8

答案 1 :(得分:-2)

如果它的格式与youtube.com/watch?v=相同,则可以将其拆分为:

your_url = www.youtube.com/watch?v=wMXHHuEGuO8
splited = your_url.split('watch?v=') 
# you will have a list of two elements, first one is
# www.youtube.com/ and the other one is wMXHHuEGuO8