'Extracting video url from extended entities object in Tweet (Python)

I am trying to use the Twitter API to get the video url when my bot is mentioned in a Tweet. After 2 days of trial and error I realized that the extended entities object already contains the .mp4 url that I need. My question is how do I extract that url from the object in Python?

When I print this code

if 'media' in mention.entities:
   for media in mention.extended_entities['media']:
      print(mention.extended_entities)

I get this output

{
'media': [
{'id': 1500560443xxxxxxxxxxxxxxxx, 'id_str': '1500xxxxxxxx', 'indices': [21, 44], 'media_url': 'http://pbs.twimg.com/ext_tw_video_thumb/15009490xxxxxxxx/pu/img/Rv9FkhcGw3xxxxxxxx.jpg', 'media_url_https': 'https://pbs.twimg.com/ext_tw_video_thumb/15005604xxxxxxxx/pu/img/Rv9FkhcGw3xxxxxxxx.jpg', 'url': 'https://twitter.com/DmwjxxxxxCBZ', 'display_url': 'pic.twitter.com/DmwjxxxxxxxxZ', 'expanded_url': 'https://twitter.com/Isxxxxxxxxy/status/15005604xxxxxxxx72/video/1', 'type': 'video', 'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'}, 'medium': {'w': 1200, 'h': 675, 'resize': 'fit'}, 'small': {'w': 680, 'h': 383, 'resize': 'fit'}, 'large': {'w': 1280, 'h': 720, 'resize': 'fit'}}, 'video_info': {'aspect_ratio': [16, 9], 'duration_millis': 8428,
'variants': [
{'bitrate': 832000, 
'content_type': 'video/mp4',
'url': **'https://video.twimg.com/ext_tw_video/15005xxxxxxxx00949250/pu/vid/640x360/HASv5xxxxxxxx2e31-F20.mp4?tag=12'**},...extra stuff...

I want only the url inside the double asterisks above. I don't want to have to loop through the entire string or use a regex. Is there any way I can pull that url from extended_entities without all the hassle?



Solution 1:[1]

I figured it out. If there's a simpler way to do this or if my new code could get an error in the future please let me know.

video_values = mention.extended_entities['media'][0]['video_info']['variants']
    i = 0
    for x in video_values:
        if "video/mp4" in mention.extended_entities['media'][0]['video_info']['variants'][i]['content_type']:
            url = mention.extended_entities['media'][0]['video_info']['variants'][i]['url']
            return url
        else:
            i += 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ugo Chaekwe