Can't list youtube videos from playlist - python

I'm trying to get and store the videos from a youtube playlist into an list in python. I followed the instructions in the docs https://developers.google.com/youtube/v3/docs/playlistItems/list but it cant seem to retrieve the video ID.
def list_playlist_localizations(youtube, playlist_id):
results = youtube.playlists().list(
part='snippet, contentDetails', id=playlist_id, maxResults=5
).execute()
#print results
for playlist_item in results['items']:
title = playlist_item['snippet']['title']
video_id = playlist_item['snippet']['resourceId']['videoId']
print video_id
EDIT:
from hyper import HTTPConnection
import random
import requests
playlist_id = "PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG"
links = []
token = '' # to get ID to next page CDIQAA
# https://stackoverflow.com/questions/14173428/how-to-change-page-results-with-youtube-data-api-v3 - reference
s = requests.Session()
r = s.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=' + playlist_id + '&key={MY_KEY}')
data = r.json()
while 'nextPageToken' in data and len(data) < 200:
token = data['nextPageToken']
r = s.get('https://www.googleapis.com/youtube/v3/playlistItems?pageToken='
+ token +
'&part=snippet&maxResults=50&playlistId='
+ playlist_id +
'&key=AIzaSyAglPb2-eVaoy1muXclkUrfPFtdYEaUcCw')
data = r.json()
for items in data['items']:
links.append('https://www.youtube.com/watch?v=' + items['snippet']['resourceId']['videoId'])
r = s.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=' + playlist_id + '&key={MY_KEY}')
data = r.json()
# Add the remaining links
for items in data['items']:
links.append('https://www.youtube.com/watch?v=' + items['snippet']['resourceId']['videoId'])
'''
for items in links:
print items
'''
print "num items: " + str(len(links))
print "Random link: "
print links[random.randint(0, len(links) - 1)]
This is my implementation to generate random youtube links from a playlist

You can get the data use html requests
And you will get the playlist as JSON data
For example
import requests,json
key = 'YOUR API KEY'
playlistid = 'PLBCF2DAC6FFB574DE'
data = json.loads(requests.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={}&key={}'.format(playlistid,key)).text)
print(data)
the resoult will be
{
"kind": "youtube#playlistItemListResponse",
"etag": "\"Wu2llbfqCdxIVjGbVPm2DslKPCA/_HwI6Wa-Ku-4k5VAHT1GRPH2his\"",
"nextPageToken": "CAUQAA",
"pageInfo": {
"totalResults": 13,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#playlistItem",
"etag": "\"Wu2llbfqCdxIVjGbVPm2DslKPCA/4MX9K88_OdrfvVVaQ2ys5BdQtI8\"",
"id": "UExCQ0YyREFDNkZGQjU3NERFLkE2OTA3QzIwNEI3RjYxMDE=",
"snippet": {
"publishedAt": "2013-10-18T14:55:24.000Z",
"channelId": "UCvceBgMIpKb4zK1ss-Sh90w",
"title": "Andrew Willis, Skatepark Engineer",
"description": "Andrew Willis built a skatepark in East London using reclaimed materials left over from the Olympic Games, creating a lasting legacy for the local community of Hackney Wick.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/GvgqDSnpRQM/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/GvgqDSnpRQM/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/GvgqDSnpRQM/hqdefault.jpg",
"width": 480,
"height": 360
},
"standard": {
"url": "https://i.ytimg.com/vi/GvgqDSnpRQM/sddefault.jpg",
"width": 640,
"height": 480
}
},
"channelTitle": "Google Search Stories",
"playlistId": "PLBCF2DAC6FFB574DE",
"position": 0,
"resourceId": {
"kind": "youtube#video",
"videoId": "GvgqDSnpRQM"
}
}
},
{
"kind": "youtube#playlistItem",
"etag": "\"Wu2llbfqCdxIVjGbVPm2DslKPCA/PBY3vMCXQ8JLWA2_X9BSSpasHUo\"",
"id": "UExCQ0YyREFDNkZGQjU3NERFLjU5NzE2QkNERURDRTE5NDc=",
"snippet": {
"publishedAt": "2011-09-23T04:52:44.000Z",
"channelId": "UCvceBgMIpKb4zK1ss-Sh90w",
"title": "Private video",
"description": "This video is private.",
"channelTitle": "Google Search Stories",
"playlistId": "PLBCF2DAC6FFB574DE",
"position": 1,
"resourceId": {
"kind": "youtube#video",
"videoId": "fIc_VEQ7Vo0"
}
}
},
{
"kind": "youtube#playlistItem",
"etag": "\"Wu2llbfqCdxIVjGbVPm2DslKPCA/y4jkKn0lC3ggyxUi8Xr1NXcGPjA\"",
"id": "UExCQ0YyREFDNkZGQjU3NERFLkZGQjNGMEFDQ0U0MzBCMzc=",
"snippet": {
"publishedAt": "2011-11-22T15:29:40.000Z",
"channelId": "UCvceBgMIpKb4zK1ss-Sh90w",
"title": "Mark Lesek: A New/Old Prosthetic",
"description": "Follow Mark on Google+: https://plus.google.com/u/0/114778778979884307299/about\r\n\r\nMark lost his arm several years ago. Now his search for a better prosthetic could improve the lives of amputees everywhere.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/V4DDt30Aat4/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/V4DDt30Aat4/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/V4DDt30Aat4/hqdefault.jpg",
"width": 480,
"height": 360
},
"standard": {
"url": "https://i.ytimg.com/vi/V4DDt30Aat4/sddefault.jpg",
"width": 640,
"height": 480
}
},
"channelTitle": "Google Search Stories",
"playlistId": "PLBCF2DAC6FFB574DE",
"position": 2,
"resourceId": {
"kind": "youtube#video",
"videoId": "V4DDt30Aat4"
}
}
},
{
"kind": "youtube#playlistItem",
"etag": "\"Wu2llbfqCdxIVjGbVPm2DslKPCA/9uUzwGG9HqDu7g3ZMZw3TYWlBOs\"",
"id": "UExCQ0YyREFDNkZGQjU3NERFLkFBRDU2ODRCNTgwMzA2RTQ=",
"snippet": {
"publishedAt": "2011-10-20T01:02:11.000Z",
"channelId": "UCvceBgMIpKb4zK1ss-Sh90w",
"title": "Private video",
"description": "This video is private.",
"channelTitle": "Google Search Stories",
"playlistId": "PLBCF2DAC6FFB574DE",
"position": 3,
"resourceId": {
"kind": "youtube#video",
"videoId": "07718Vcwcyc"
}
}
},
{
"kind": "youtube#playlistItem",
"etag": "\"Wu2llbfqCdxIVjGbVPm2DslKPCA/x8utLR6SK07clGh9DQzv80Mczyw\"",
"id": "UExCQ0YyREFDNkZGQjU3NERFLkMyQjUzQkM1OTFFRTNFMEQ=",
"snippet": {
"publishedAt": "2011-11-22T15:29:40.000Z",
"channelId": "UCvceBgMIpKb4zK1ss-Sh90w",
"title": "Mark Kempton: Neighbors In Need",
"description": "Follow Mark on Google+: https://profiles.google.com/u/0/105705606437451864842\r\n\r\nWhen floodwaters hit northeast Australia, Mark's innovative search became the difference between life and death for many of his neighbors.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/XDgC4FMftpg/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/XDgC4FMftpg/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/XDgC4FMftpg/hqdefault.jpg",
"width": 480,
"height": 360
},
"standard": {
"url": "https://i.ytimg.com/vi/XDgC4FMftpg/sddefault.jpg",
"width": 640,
"height": 480
}
},
"channelTitle": "Google Search Stories",
"playlistId": "PLBCF2DAC6FFB574DE",
"position": 4,
"resourceId": {
"kind": "youtube#video",
"videoId": "XDgC4FMftpg"
}
}
}
]
}

Related

Importing a JSON object to a Google Cloud SQL instance authentication error

I have been stuck on this for the last 2 days, first time in a long time I had to use stackoverflow. But I love this community
What I am trying to do?
I am trying to upload a JSON object to update a table in a cloud SQL instance.
Error I am getting
I have tried using a service account and 02Auth credentials but I still get these errors.
Code below
from pprint import pprint
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from google.oauth2 import service_account
import google.auth.credentials
credentials = GoogleCredentials.get_application_default()
quota_project_id = "alert-groove-360914"
scopes = ["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/sqlservice.admin"]
#credentials, _ = google.auth.load_credentials_from_file(
# "alert-groove-360914-0d5821a7921c.json", scopes=scopes, quota_project_id=quota_project_id
# )
#credentials = service_account.Credentials.from_service_account_file("alert-groove-360914-0d5821a7921c.json")
service = discovery.build('sqladmin', 'v1beta4', credentials=credentials)
# Project ID of the project that contains the instance.
project = 'XXXXXXXX' # TODO: Update placeholder value.
# Cloud SQL instance ID. This does not include the project ID.
instance = 'employment-types' # TODO: Update placeholder value.
database_instance_body = {
"id": 3,
"first_name": "XXXXXXXX",
"last_name": "XXXXXXX",
"email": "XXXXXX28#gmail.com",
"mobile_number": "XXXXXXXXX",
"country_id": 224,
"new_user": False,
"status": 1,
"reason": 'null',
"duration": 'null',
"linkedin_id": 'null',
"sync_contacts": False,
"linkedin_sync": False,
"available": True,
"radar_visibility": 'null',
"details": {
"organization": "Foras",
"isSelfEmployed": False,
"gender_id": 2,
"location_id": 457,
"gender": 'null',
"about": "The best around and nothing will ever get me down",
"image": "https:\/\/foras.tedmob.com\/storage\/users\/image-8596.jpg",
"lat": "25.20082000253009",
"long": "55.280527271443894",
"Gender_Rel": "Male",
"job_title": "Engineer",
"Experience": "10+ years",
"Location": "Dubai"
},
"interests": [
{
"id": 106,
"title": "Nightlife",
"icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
"image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
"category": {
"category": "Culture"
}
},
{
"id": 102,
"title": "Music",
"icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
"image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
"category": {
"category": "Culture"
}
},
{
"id": 98,
"title": "Personal finance",
"icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
"image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
"category": {
"category": "Finance"
}
},
{
"id": 101,
"title": "Crypto currency ",
"icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
"image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
"category": {
"category": "Finance"
}
},
{
"id": 104,
"title": "Breaking",
"icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
"image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
"category": {
"category": "Culture"
}
}
],
"languages": [],
"goals": [
{
"id": 2,
"title": "Find a new job",
"icon": "https:\/\/foras.tedmob.com\/storage\/goals\/find-a-new-job-6804.png",
"pivot": {
"user_id": 3,
"goal_id": 2
},
"category": {
"category": "Career"
}
},
{
"id": 11,
"title": "Explore a career change",
"icon": "https:\/\/foras.tedmob.com\/storage\/goals\/explore-a-career-change-5885.png",
"pivot": {
"user_id": 3,
"goal_id": 11
},
"category": {
"category": "Career"
}
},
{
"id": 12,
"title": "Find co-founders",
"icon": "https:\/\/foras.tedmob.com\/storage\/goals\/find-co-founders-2170.png",
"pivot": {
"user_id": 3,
"goal_id": 12
},
"category": {
"category": "Networking"
}
}
],
"country": {
"id": 224,
"name": "United Arab Emirates",
"iso": "AE",
"phone_code": "+971"
},
"academic_levels": [
{
"id": 4,
"title": "Master's degree",
"pivot": {
"user_id": 3,
"academic_level_id": 4
}
}
],
"experiences": [
{
"id": 1,
"title": "test1",
"company_name": "test",
"isCurrentlyWorking": True,
"start_date": "2021-06-15 00:00:00",
"end_date": "2022-09-13 00:00:00",
"end_position": True,
"headline": "test",
"industry": "test",
"description": "description",
"employment_type": 1
}
]
}
request = service.instances().update(project=project, instance=instance, body=database_instance_body)
request.execute()

Fliter out live videos from youtube search api

I am trying to get videos using search query with youtube v3 api Search: list.
My query body is something like follows :
request = youtube.search().list(
part="snippet",
maxResults=40,
q="Cat work york"
)
But the problem is, it returns live videos among other regular videos. I dont want live videos to be returned, how can I do that ? please help me here.
Thanks
Try this https://developers.google.com/youtube/v3/docs/search/list with the following filters:
part="snippet",
q="/-Live",
safeSearch="strict",
type="video
I think you should try passing this parameter :
broadcastStatus="completed"
Here is the reference :
https://developers-dot-devsite-v2-prod.appspot.com/youtube/v3/live/docs/liveBroadcasts/list#parameters
I tried with this request and I got no live videos - without need of additional filters:
URL:
https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=10&q=Cat%20work%20york&type=video&key=[YOUR_API_KEY]
And these are the results of the first page:
{
"kind": "youtube#searchListResponse",
"etag": "-KMpLk38ZnJHhWd5fPfmwou7bX4",
"nextPageToken": "CAoQAA",
"regionCode": "CO",
"pageInfo": {
"totalResults": 1000000,
"resultsPerPage": 10
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "fe7kdo2hrlF2OjEpk8Nd1kbStFw",
"id": {
"kind": "youtube#video",
"videoId": "jDoVckC6NhA"
},
"snippet": {
"publishedAt": "2015-07-30T21:25:54Z",
"channelId": "UC9k-yiEpRHMNVOnOi_aQK8w",
"title": "Woman Endures Cat Calls Walking in Street: 'It Makes You Feel Like A Fool'",
"description": "Cosmopolitan magazine is getting a lot of attention for a video they posted to their website of women facing a barrage of cat calls just by walking down the streets ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/jDoVckC6NhA/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/jDoVckC6NhA/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/jDoVckC6NhA/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "Inside Edition",
"liveBroadcastContent": "none",
"publishTime": "2015-07-30T21:25:54Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "k0tqw-tDAsnJZ5HJjBmHXZyiaiY",
"id": {
"kind": "youtube#video",
"videoId": "aAxx1EZwDIY"
},
"snippet": {
"publishedAt": "2016-02-13T05:35:16Z",
"channelId": "UC-2ePlhDlfJyzU7vypHFgBQ",
"title": "2 night races in traffic (cat & mouse)!!",
"description": "what i normally encounter on my way home !!",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/aAxx1EZwDIY/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/aAxx1EZwDIY/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/aAxx1EZwDIY/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "Daily Street Racing",
"liveBroadcastContent": "none",
"publishTime": "2016-02-13T05:35:16Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "grZqq0QA-Z1xxcNDM4Iukhqx3GI",
"id": {
"kind": "youtube#video",
"videoId": "nMlJJKNWQZY"
},
"snippet": {
"publishedAt": "2018-06-24T13:00:04Z",
"channelId": "UCINb0wqPz-A0dV9nARjJlOQ",
"title": "Cat Runs A Real Estate Office In Brooklyn | The Dodo City Pets",
"description": "This Cat Runs A Real Estate Office In Brooklyn | Valentino's dad found him as a stray and brought him to work at his real estate office in Carroll Gardens, ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/nMlJJKNWQZY/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/nMlJJKNWQZY/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/nMlJJKNWQZY/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "The Dodo",
"liveBroadcastContent": "none",
"publishTime": "2018-06-24T13:00:04Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "SzycZTHAXxzRnxJH7pl1H-3AHhc",
"id": {
"kind": "youtube#video",
"videoId": "ZUO9ijDjXTg"
},
"snippet": {
"publishedAt": "2020-08-14T03:04:14Z",
"channelId": "UCcl8P4rYjdbxbFTXxkNXuZQ",
"title": "Mega Hits 2020 🍍 Best Of Vocal Deep House Summer Music Mix 🍍 Deep Feeling By ChilledVibes Live #7",
"description": "Mega Hits 2020 Best Of Vocal Deep House Summer Music Mix Deep Feeling By ChilledVibes Live #7 #SummerMusicMix #BestOfDeepHouse ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/ZUO9ijDjXTg/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/ZUO9ijDjXTg/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/ZUO9ijDjXTg/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "ChilledVibes",
"liveBroadcastContent": "none",
"publishTime": "2020-08-14T03:04:14Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "nNSPJNKlYZWYA5FDN96Jv9nFygk",
"id": {
"kind": "youtube#video",
"videoId": "-JOy1nM6UoA"
},
"snippet": {
"publishedAt": "2008-04-21T03:37:32Z",
"channelId": "UCmSOMw225KDZwqOsLFe9GSw",
"title": "CAT POWER - New York",
"description": "Snail is sad but determined to make things work in NYC, with music by Cat Power.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/-JOy1nM6UoA/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/-JOy1nM6UoA/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/-JOy1nM6UoA/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "puppetbully",
"liveBroadcastContent": "none",
"publishTime": "2008-04-21T03:37:32Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "HUmDdgYk1jz3lv6cNhiZLyqek8c",
"id": {
"kind": "youtube#video",
"videoId": "XcAH4OMPlDs"
},
"snippet": {
"publishedAt": "2020-04-17T15:53:42Z",
"channelId": "UCUw3KEvEX49JlnYhlneD-CA",
"title": "Running the York Cat Trail During Lockdown April 2020",
"description": "For anyone who would like to experience the York Cat Trail but who can't get to York. Come with me on a 12 minute whistle stop tour of the cats on buildings in ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/XcAH4OMPlDs/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/XcAH4OMPlDs/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/XcAH4OMPlDs/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "The Cat Gallery",
"liveBroadcastContent": "none",
"publishTime": "2020-04-17T15:53:42Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "B6Mx6RpMg8UXlABqaFPgJd_EOqk",
"id": {
"kind": "youtube#video",
"videoId": "df7g19GzFkg"
},
"snippet": {
"publishedAt": "2019-11-05T02:24:12Z",
"channelId": "UCDVYQ4Zhbm3S2dlz7P1GBDg",
"title": "Cat on the Field Scores 50-Yd TD Run! 🐾",
"description": "A fluffy feline makes its way onto the field and somehow gets to the end zone for a touchdown! The Dallas Cowboys take on the New York Giants during Week 9 ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/df7g19GzFkg/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/df7g19GzFkg/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/df7g19GzFkg/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "NFL",
"liveBroadcastContent": "none",
"publishTime": "2019-11-05T02:24:12Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "k5CXKp3kDIqnyqT03Vxj9_tMdKg",
"id": {
"kind": "youtube#video",
"videoId": "j0RgF_AL5vk"
},
"snippet": {
"publishedAt": "2018-08-31T02:11:05Z",
"channelId": "UC4L0b4TTnV_dK67pWxPxPXA",
"title": "FAT CAT PUT ALL THAT WORK IN AND TURNED ON PAPPY MASON HE IS NOW IN ADX SUFFERING 🤦🏽‍♂️😢",
"description": "Fat cat TRIPLE DOUBLE CROSSER.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/j0RgF_AL5vk/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/j0RgF_AL5vk/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/j0RgF_AL5vk/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "KING EARNER",
"liveBroadcastContent": "none",
"publishTime": "2018-08-31T02:11:05Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "QM6IfM0553SCG8Lb21omcpVmZ2k",
"id": {
"kind": "youtube#video",
"videoId": "4cb1YIsyty4"
},
"snippet": {
"publishedAt": "2016-09-12T14:18:43Z",
"channelId": "UCEcDA5zAfZTVr93HoUzYf_w",
"title": "Cat® Power Box Rake Attachment Operating Tips",
"description": "http://www.cat.com/en_US/products/new/attachments/rakes.html | Learn operating tips for the Power Box Rake work tool attachment for Skid Steer Loaders, ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/4cb1YIsyty4/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/4cb1YIsyty4/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/4cb1YIsyty4/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "Cat Landscaping and Construction",
"liveBroadcastContent": "none",
"publishTime": "2016-09-12T14:18:43Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "gXii2GJAAanIFjYjqeIZvsctnHI",
"id": {
"kind": "youtube#video",
"videoId": "4pq9N8qrTT0"
},
"snippet": {
"publishedAt": "2020-07-14T14:23:32Z",
"channelId": "UChLtXXpo4Ge1ReTEboVvTDg",
"title": "''Rocco, put your tail down": Cat interrupts virtual UK parliamentary meeting",
"description": "A member of the UK parliament's cat interrupted a live virtual committee meeting on Tuesday, prompting laughter from others on the call. John Nicolson was ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/4pq9N8qrTT0/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/4pq9N8qrTT0/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/4pq9N8qrTT0/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "Global News",
"liveBroadcastContent": "none",
"publishTime": "2020-07-14T14:23:32Z"
}
}
]
}
If you still got "live videos", add the videoDuration=medium filter in the URL request.

Getting specific lines from a print in Python with Spotipy

I am writing some code with Python and Spotipy and I'm relatively new to coding. I have some code that get all the info about a Spotify playlist and prints it out for me:
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
import json
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
playlist_id = 'spotify:playlist:76CVeJDw2b90up5PgkZXyU'
results = sp.playlist(playlist_id)
#print(json.dumps(results, indent=4))
print((json.dumps(results, indent=4)))
It works well and gives me all the info. My problem is that I only need specifics from the print:
"collaborative": false,
"description": "",
"external_urls": {
"spotify": "https://open.spotify.com/playlist/76CVeJDw2b90up5PgkZXyU"
},
"followers": {
"href": null,
"total": 0
},
"href": "https://api.spotify.com/v1/playlists/76CVeJDw2b90up5PgkZXyU?additional_types=track",
"id": "76CVeJDw2b90up5PgkZXyU",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/ab67616d0000b2734a052b99c042dc15f933145b",
"width": 640
}
],
"name": "TEST",
"owner": {
"display_name": "Name",
"external_urls": {
"spotify": "https://open.spotify.com/user/myname"
},
"href": "https://api.spotify.com/v1/users/myname",
"id": "Myname",
"type": "user",
"uri": "spotify:user:kovizsombor"
},
"primary_color": null,
"public": true,
"snapshot_id": "MixmMGE0MDgxNDQ1ZGVlNmE4MThiMmQwODMwYWU0OTI3YzkyOGJhOWIz",
"tracks": {
"href": "https://api.spotify.com/v1/playlists/76CVeJDw2b90up5PgkZXyU/tracks?offset=0&limit=100&additional_types=track",
"items": [
{
"added_at": "2020-05-17T10:00:11Z",
"added_by": {
"external_urls": {
"spotify": "https://open.spotify.com/user/kovizsombor"
},
"href": "https://api.spotify.com/v1/users/kovizsombor",
"id": "kovizsombor",
"type": "user",
"uri": "spotify:user:kovizsombor"
},
"is_local": false,
"primary_color": null,
"track": {
"album": {
"album_type": "album",
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/0PFtn5NtBbbUNbU9EAmIWF"
},
"href": "https://api.spotify.com/v1/artists/0PFtn5NtBbbUNbU9EAmIWF",
"id": "0PFtn5NtBbbUNbU9EAmIWF",
"name": "TOTO",
"type": "artist",
"uri": "spotify:artist:0PFtn5NtBbbUNbU9EAmIWF"
}
],
],
"external_urls": {
"spotify": "https://open.spotify.com/album/62U7xIHcID94o20Of5ea4D"
},
"href": "https://api.spotify.com/v1/albums/62U7xIHcID94o20Of5ea4D",
"id": "62U7xIHcID94o20Of5ea4D",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/ab67616d0000b2734a052b99c042dc15f933145b",
"width": 640
},
{
"height": 300,
"url": "https://i.scdn.co/image/ab67616d00001e024a052b99c042dc15f933145b",
"width": 300
},
{
"height": 64,
"url": "https://i.scdn.co/image/ab67616d000048514a052b99c042dc15f933145b",
"width": 64
}
],
"name": "Toto IV",
"release_date": "1982-04-08",
"release_date_precision": "day",
"total_tracks": 10,
"type": "album",
"uri": "spotify:album:62U7xIHcID94o20Of5ea4D"
},
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/0PFtn5NtBbbUNbU9EAmIWF"
},
"href": "https://api.spotify.com/v1/artists/0PFtn5NtBbbUNbU9EAmIWF",
"id": "0PFtn5NtBbbUNbU9EAmIWF",
"name": "TOTO",
"type": "artist",
"uri": "spotify:artist:0PFtn5NtBbbUNbU9EAmIWF"
}
],
"available_markets": [
],
"disc_number": 1,
"duration_ms": 295893,
"episode": false,
"explicit": false,
"external_ids": {
"isrc": "USSM19801941"
},
"external_urls": {
"spotify": "https://open.spotify.com/track/2374M0fQpWi3dLnB54qaLX"
},
"href": "https://api.spotify.com/v1/tracks/2374M0fQpWi3dLnB54qaLX",
"id": "2374M0fQpWi3dLnB54qaLX",
"is_local": false,
"name": "Africa",
"popularity": 83,
"preview_url": "https://p.scdn.co/mp3-preview/dd78dafe31bb98f230372c038a126b8808f9349b?cid=d568e7073a38465bba48268ea9f10153",
"track": true,
"track_number": 10,
"type": "track",
"uri": "spotify:track:2374M0fQpWi3dLnB54qaLX"
},
"video_thumbnail": {
"url": null
}
}
],
"limit": 100,
"next": null,
"offset": 0,
"previous": null,
"total": 1
},
"type": "playlist",
"uri": "spotify:playlist:76CVeJDw2b90up5PgkZXyU"
}
From this long print I somehow need to extract the Artist and the song title and preferably make it into a variable. Also not sure how this would work if there are multiple songs in a playlist.
It's also a solution if I can print out only the Artist and the title of the song without printing out all the information.
Based on your posted example it appears that you have only 1 song named "Africa" by artist "TOTO". Copying the track to have two songs, I added another track with two artists for testing the arrays.
If that json is loaded into a variable named results then (as #xcmkz said) you have a python dictionary and can process accordingly.
Try working with the following to transverse through your dict appending artists and songs to lists:
song_dict = {}
for track in results['tracks']['items']:
song_name = track["track"]["name"]
a2 = []
for t1 in track['track']['artists']:
a2.append(t1['name'])
song_dict.update({song_name: a2})
print(f'Dictionary of Songs and Artists:')
for k, v in song_dict.items():
print(f'Song --> {k}, by --> {", ".join(v)}')
Results:
Dictionary of Songs and Artists:
Song --> Africa, by --> TOTO
Song --> Just Another Silly Song, by --> Artist 2, Artist 3
sp.playlist returns a dictionary, so you can simply access its values by their keys. For example:
>>> results['name']
'TEST'
JSON is a data serialization format, ie a standardized way of representing objects as pure text and parsing them back from the text. json.dumps therefore converts the dictionary object to a string of text. This is useful if you want to for example save the results to a file and load it back later. You don't need it to access contents from results.
(This is a playlist though—you will need to get information on each song/track to get its artist and name.)

How to get the actual music in Spotify using python?

I downloaded the Spotify App on my Windows 10 and installed. So I had the ideia of make a software that need to get the music that is running at the moment. Is it possible to get It? It os not necessary the code. I just want to know where to start, because I did not find anything about It. I would rather do It using python.
You can use the Get the User's Currently Playing Track endpoint, documented here: https://developer.spotify.com/web-api/get-the-users-currently-playing-track/
The endpoint will return JSON that includes information about the track, for example:
{
"context": {
"external_urls" : {
"spotify" : "http://open.spotify.com/user/spotify/playlist/49znshcYJROspEqBoHg3Sv"
},
"href" : "https://api.spotify.com/v1/users/spotify/playlists/49znshcYJROspEqBoHg3Sv",
"type" : "playlist",
"uri" : "spotify:user:spotify:playlist:49znshcYJROspEqBoHg3Sv"
},
"timestamp": 1490252122574,
"progress_ms": 44272,
"is_playing": true,
"item": {
"album": {
"album_type": "album",
"external_urls": {
"spotify": "https://open.spotify.com/album/6TJmQnO44YE5BtTxH8pop1"
},
"href": "https://api.spotify.com/v1/albums/6TJmQnO44YE5BtTxH8pop1",
"id": "6TJmQnO44YE5BtTxH8pop1",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/8e13218039f81b000553e25522a7f0d7a0600f2e",
"width": 629
},
{
"height": 300,
"url": "https://i.scdn.co/image/8c1e066b5d1045038437d92815d49987f519e44f",
"width": 295
},
{
"height": 64,
"url": "https://i.scdn.co/image/d49268a8fc0768084f4750cf1647709e89a27172",
"width": 63
}
],
"name": "Hot Fuss",
"type": "album",
"uri": "spotify:album:6TJmQnO44YE5BtTxH8pop1"
},
"artists": [
{
"external_urls": {
"spotify": "https://open.spotify.com/artist/0C0XlULifJtAgn6ZNCW2eu"
},
"href": "https://api.spotify.com/v1/artists/0C0XlULifJtAgn6ZNCW2eu",
"id": "0C0XlULifJtAgn6ZNCW2eu",
"name": "The Killers",
"type": "artist",
"uri": "spotify:artist:0C0XlULifJtAgn6ZNCW2eu"
}
],
"available_markets": [
"AD",
"AR",
...
"TW",
"UY"
],
"disc_number": 1,
"duration_ms": 222075,
"explicit": false,
"external_ids": {
"isrc": "USIR20400274"
},
"external_urls": {
"spotify": "https://open.spotify.com/track/0eGsygTp906u18L0Oimnem"
},
"href": "https://api.spotify.com/v1/tracks/0eGsygTp906u18L0Oimnem",
"id": "0eGsygTp906u18L0Oimnem",
"name": "Mr. Brightside",
"popularity": 0,
"preview_url": "http://d318706lgtcm8e.cloudfront.net/mp3-preview/f454c8224828e21fa146af84916fd22cb89cedc6",
"track_number": 2,
"type": "track",
"uri": "spotify:track:0eGsygTp906u18L0Oimnem"
}
}
If you want even more info about the track, you can use the id you get from this endpoint to call any of the Track endpoints here: https://developer.spotify.com/web-api/track-endpoints/. There are lots of fun things you can do, like audio features or analysis.

Getting a KeyError when trying to iterate a Python dict obtained using OpenCalais

I am trying to tag content using OpenCalais. The following is my code that I'm using the communicate with the API:
import httplib2
import json
import ast
# Some local values needed for the call
LOCAL_API_KEY = '***********************' # Aquire this by registering at the Calais site
CALAIS_TAG_API = 'https://api.thomsonreuters.com/permid/calais'
# Some sample text from a news story to pass to Calais for analysis
test_body = 'Samsung is closing its Milk Music streaming service'
# header information need by Calais.
# For more info see http://www.opencalais.com/documentation/calais-web-service-api/api-invocation/rest
headers = {
'X-AG-Access-Token': LOCAL_API_KEY,
'Content-Type': 'text/raw',
'outputFormat': 'application/json',
}
# Create your http object
http = httplib2.Http()
# Make the http post request, passing the body and headers as needed.
response, content = http.request(CALAIS_TAG_API, 'POST', headers=headers, body=test_body)
jcontent = json.loads(content) # Parse the json return into a python dict
output = json.dumps(jcontent, indent=4) # Pretty print the resulting dictionary returned.
print output
Anyway, this works nicely, as I am able to get the following output (print output).
{
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/cat/1": {
"score": 1,
"forenduserdisplay": "false",
"name": "Business_Finance",
"_typeGroup": "topics"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/cat/2": {
"score": 1,
"forenduserdisplay": "false",
"name": "Entertainment_Culture",
"_typeGroup": "topics"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/lid/DefaultLangId": {
"forenduserdisplay": "false",
"language": "http://d.opencalais.com/lid/DefaultLangId/InputTextTooShort",
"_typeGroup": "language"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/Industry/1": {
"name": "Phones & Handheld Devices - NEC",
"permid": "4294951233",
"forenduserdisplay": "false",
"_typeGroup": "industry",
"relevance": 0.8,
"rcscode": "B:1768"
},
"http://d.opencalais.com/comphash-1/c021d644-16e9-3060-96fe-b3be0cd4ae1e": {
"_typeReference": "http://s.opencalais.com/1/type/em/e/Company",
"_type": "Company",
"name": "Samsung",
"confidence": {
"aggregate": "0.905",
"resolution": "1.0",
"statisticalfeature": "0.876",
"dblookup": "0.0"
},
"_typeGroup": "entities",
"instances": [
{
"detection": "[]Samsung[ is closing its Milk Music streaming]",
"length": 7,
"exact": "Samsung",
"suffix": " is closing its Milk Music streaming",
"offset": 0
}
],
"confidencelevel": "0.905",
"relevance": 0.8,
"nationality": "N/A",
"resolutions": [
{
"name": "SAMSUNG ELECTRONICS CO,.LTD",
"permid": "4295882451",
"commonname": "Samsung Elec",
"primaryric": "005930.KS",
"score": 1,
"ticker": "005930",
"id": "https://permid.org/1-4295882451"
}
],
"forenduserdisplay": "false"
},
"doc": {
"info": {
"document": "Samsung is closing its Milk Music streaming service",
"docId": "http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1",
"docDate": "2016-08-22 13:02:01.814",
"docTitle": "",
"ontology": "http://mdaas-virtual-onecalais.int.thomsonreuters.com/owlschema/9.8/onecalais.owl.allmetadata.xml",
"calaisRequestID": "eef490a6-2e3e-7cac-156b-257ebcf3beba",
"id": "http://id.opencalais.com/b*RzenPxfvWZmjCvQqpzNA"
},
"meta": {
"stagsVer": "OneCalais_9.8-RELEASE-b6-2016-07-18_14:00:15",
"contentType": "text/raw",
"language": "InputTextTooShort",
"serverVersion": "OneCalais_9.8-RELEASE:109",
"submissionDate": "2016-08-22 13:02:01.679",
"processingVer": "AllMetadata",
"submitterCode": "0ca6a864-5659-789d-5f32-f365f695e757",
"signature": "digestalg-1|BovyytInhxJhSerNjEFvOZNAHJQ=|Q5g9GCOSi7+FnERjgY9y4B9oJukYPjYeTl6v+Zu81BJLwOBcIZZ/eA=="
}
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/ComponentVersions": {
"version": [
"Deals Index:201608221149:201608221149",
"index-refineries:201608202306:201608202306",
"config-physicalAssets-powerStations:480:480",
"OA Index:201608212349:201608212349",
"NextTags:OneCalais_9.8-RELEASE:109",
"config-sca-DataPackage:38:38",
"com.clearforest.infoext.dial4j.plugins-basistechconfig:OneCalais_9.8-RELEASE:109",
"People Index:201608221124:201608221124",
"config-negativeSignature:480:480",
"Dial4J:OneCalais_8.6-RELEASE:209",
"OA Override:507:507",
"People Override:480:480",
"index-vessels:201608201644:201608201644",
"config-refineries:480:480",
"config-cse:507:507",
"config-vessels:480:480",
"OneCalais:OneCalais_9.8-RELEASE:109",
"config-physicalAssets-mines:480:480",
"SocialTags Index:201608212334:201608212334",
"BlackList:504:504",
"index-ports:201608202256:201608202256",
"config-physicalAssets-ports:480:480",
"config-drugs:480:480"
],
"_typeGroup": "versions"
},
"http://d.opencalais.com/comphash-1/e89d0187-8b46-3f8d-9f6b-4995a709c85e": {
"_typeReference": "http://s.opencalais.com/1/type/em/e/Company",
"_type": "Company",
"name": "Milk Music",
"confidence": {
"aggregate": "0.499",
"resolution": "0.0",
"statisticalfeature": "0.775",
"dblookup": "0.0"
},
"_typeGroup": "entities",
"instances": [
{
"suffix": " streaming service",
"prefix": "Samsung is closing its ",
"detection": "[Samsung is closing its ]Milk Music[ streaming service]",
"length": 10,
"offset": 23,
"exact": "Milk Music"
}
],
"confidencelevel": "0.499",
"relevance": 0.8,
"nationality": "N/A",
"forenduserdisplay": "false"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/cat/3": {
"score": 1,
"forenduserdisplay": "false",
"name": "Technology_Internet",
"_typeGroup": "topics"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/1": {
"name": "Streaming music services",
"importance": "1",
"_typeGroup": "socialTag",
"originalValue": "Streaming music services",
"socialTag": "http://d.opencalais.com/genericHasher-1/d1447a37-4c52-3b2f-a9d2-40984014685b",
"forenduserdisplay": "true",
"id": "http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/1"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/3": {
"name": "Milk Music",
"importance": "1",
"_typeGroup": "socialTag",
"originalValue": "Milk Music (streaming service)",
"socialTag": "http://d.opencalais.com/genericHasher-1/471ee9b8-9f72-3a81-aa13-2a7d44658521",
"forenduserdisplay": "true",
"id": "http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/3"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/2": {
"name": "Digital audio",
"importance": "1",
"_typeGroup": "socialTag",
"originalValue": "Digital audio",
"socialTag": "http://d.opencalais.com/genericHasher-1/64447afb-045b-34db-9a52-dae5bed0254e",
"forenduserdisplay": "true",
"id": "http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/2"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/5": {
"name": "Smartphones",
"importance": "2",
"_typeGroup": "socialTag",
"originalValue": "Smartphones",
"socialTag": "http://d.opencalais.com/genericHasher-1/e42d9d7b-150b-3c30-974f-87a1fba000ef",
"forenduserdisplay": "true",
"id": "http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/5"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/4": {
"name": "Samsung",
"importance": "2",
"_typeGroup": "socialTag",
"originalValue": "Samsung",
"socialTag": "http://d.opencalais.com/genericHasher-1/97370f53-c2f8-31b8-bbcf-aa685e504714",
"forenduserdisplay": "true",
"id": "http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/4"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/7": {
"name": "Samsung Galaxy",
"importance": "2",
"_typeGroup": "socialTag",
"originalValue": "Samsung Galaxy",
"socialTag": "http://d.opencalais.com/genericHasher-1/64b8e664-bbdc-3731-b712-eb30990eab6f",
"forenduserdisplay": "true",
"id": "http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/7"
},
"http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/6": {
"name": "Samsung Music Hub",
"importance": "2",
"_typeGroup": "socialTag",
"originalValue": "Samsung Music Hub",
"socialTag": "http://d.opencalais.com/genericHasher-1/a3310a01-ef6f-314e-90b2-a303822b965c",
"forenduserdisplay": "true",
"id": "http://d.opencalais.com/dochash-1/8a7adab6-d07e-38e6-b0c9-5db5220336c1/SocialTag/6"
}
}
Something I noticed is that the keys are all hyperlinks. Anyway, I want to print all the socialTags from the output. To do that, I wrote this following code:
# Print all the social tags
for key, value in ast.literal_eval(output).items():
if value["_typeGroup"] == 'socialTag':
print value["name"]
However, I get this error:
Traceback (most recent call last):
File "opencal.py", line 30, in <module>
if value["_typeGroup"] == 'socialTag':
KeyError: '_typeGroup'
What is this error? Or to be more precise, what is the correct way to get the socialTags? Thanks.

Categories

Resources