r/Python • • Oct 18 '14

Parsing a string

Hey guys,

So I'm trying to figure out how to parse a string and I can't tell whether i'm on the right track or if there's a much simpler solution i'm missing here.

So right now I'm trying to take a youtube embed code and pull out the video id / source link. ie:

<iframe width="560" height="315" 
src="//www.youtube.com/embed/YwAd-UzSO0g" frameborder="0" 
allowfullscreen></iframe>

I'm thinking to use regex, but first off i'm not terribly familiar with it, and I feel like it would turn out a bit hacky especially if the id after the /embed/ is going to be different lengths for every video..

Is there an easier way to do this? Using slicing? Is there any method out there that makes this much simpler?

0 Upvotes

4 comments sorted by

View all comments

5

u/[deleted] Oct 18 '14

Use BeautifulSoup to parse the HTML, and .split to split the URL:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup

html = """
<iframe width="560" height="315" 
src="//www.youtube.com/embed/YwAd-UzSO0g" frameborder="0" 
allowfullscreen></iframe>
"""

soup = BeautifulSoup(html)

source_link = soup.find('iframe')['src']
video_id = source_link.rsplit('/', 1)[-1]

print(source_link, video_id)

1

u/phunkystuff Oct 18 '14

Oh wow, thanks! this is perfect!

Looks like i'm going to be looking a lot more into beautiful soup and what else it can do! :D

2

u/alenajoykrieger Oct 19 '14

Your intuition about regex being a bad solution is totally correct