我想从youtube保存视频的url字段,以便我可以在我的网站中加载它。到目前为止,我在html中提出了这个:
<h3>{{video.title}}</h3>
<object width="425" height="344"><param name="movie" value="{{video.video_url}}"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="{{video.video_url}}" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
但问题是它只能以一种方式起作用。例如:
url:http://www.youtube.com/watch?v=e4lHTj9xFqE
仅当watch?
条纹且=
变为/
所以最后的网址会有点像这样
http://www.youtube.com/v/e4lHTj9xFqE
我正在考虑在保存之前使用正则表达式并替换并删除网址。如何删除watch?
,然后将=
替换为/
?还有什么更好的方法来加载html中的视频?你们的建议将非常感激。谢谢!
修改
models.py:
class Video(models.Model):
title = models.CharField(max_length=100)
video_url = models.URLField(max_length=100)
def save(self, *args, **kwargs):
new_url = (self.video_url.replace("watch?v=","v/"))
super(Video, self).save(*args, **kwargs)
if new_url:
self.video_url = new_url
答案 0 :(得分:4)
为什么正则表达式:
string = (r'http://www.youtube.com/watch?v=e4lHTj9xFqE'.replace('watch?','')).replace('=','/')
print string
#http://www.youtube.com/v/e4lHTj9xFqE
但是如果你需要regex,你可以去:
new_url = re.sub('watch\?v=','v/',self.video_url)
试试这个:
def save(self, *args, **kwargs):
new_url = re.sub('watch\?v=','v/',self.video_url)
if new_url:
self.video_url = new_url
super(Video, self).save(*args, **kwargs)
并且不要修改html
答案 1 :(得分:2)
我会使用简单的replace
video.video_url.replace("watch?v=", "v/")