Giter VIP home page Giter VIP logo

ytpy's Introduction

ytpy

CodeFactor Downloads pypi-version contributions welcome Discord Badge

Python wrapper to extract youtube data. Simple asynchronous wrapper to get youtube video or playlist data. The purpose of this project is to make it easier for developers to extract data from YouTube.

Requirements

Dependencies

  • urllib
  • aiohttp

Install

pip install --upgrade ytpy

Usage

from ytpy import YoutubeClient
import asyncio
import aiohttp

async def main(loop):
    session = aiohttp.ClientSession()

    client = YoutubeClient(session)
    
    response = await client.search('ringtone')
    print(response)

    await session.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))

Search Video by Keywords using YoutubeDataApiV3Client

https://developers.google.com/youtube/v3/docs/search

params:

  • q, string. Search key. default: empty string.
  • part, string. Valid parts: snippet, contentDetails, player, statistics, status. default: snippet.
  • type, string. Valid types: video, playlist, channel.

Example Search method

import os
import asyncio
import aiohttp
from ytpy import YoutubeDataApiV3Client

async def main(loop):
    session = aiohttp.ClientSession()
    
    # Pass the aiohttp client session
    ayt =  YoutubeDataApiV3Client(session, dev_key=os.environ["DEVELOPER_KEY"])
    
    # test search
    results = await ayt.search(q="d&e lost", 
                               search_type="video",
                               max_results=1)
    print(results)

    await session.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.close()

Examples

Check examples for the full code example

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests/examples as appropriate.

ytpy's People

Contributors

madeyoga avatar sk9712 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

ytpy's Issues

ValueError while using the wrapper

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/sly/cogs/utility.py", line 235, in youtube
    response = await client.search(query, max_results=5)
  File "/home/container/.local/lib/python3.8/site-packages/ytpy/youtube.py", line 124, in search
    start_index = (page_content.index(start_feature) + len(start_feature) + 3)
ValueError: substring not found

is the error I get when using search. My code is:

async def youtube(self, ctx, *, query=None):
        if query == None:
            await ctx.send(Emoji.info+" Please provide a search term.")
            return

        session = aiohttp.ClientSession()
        client = YoutubeClient(session)
        response = await client.search(query, max_results=5)
        await session.close()
        titles = []
        e = 0
        for i in response:
            e += 1
            titles.append(f'`{e}`. [{i["title"]}](https://www.youtube.com/watch?v='+i["id"]+')'+'\n')
        
        embed = discord.Embed(title=f"Fetched {len(titles)} results from YouTube.", 
            description=''.join(titles), color=Color.error
            )
        await ctx.send(embed=embed)

Examples

In the readme the example uses the class YoutubeApiV3Client when it should be YoutubeDataApiV3Client.

Extract search results & music tracks from raw json (Youtube Music)

ytpy/ytpy/youtube.py

Lines 160 to 171 in 10c2915

async def search_music(self, q):
headers = {"Referer": "music.youtube.com"}
params = {
"alt": "json",
"key": self.YT_MUSIC_KEY
}
response = await self.session.post(self.YT_MUSIC_URI_PREFIX + urllib.parse.urlencode(params),
data=self.YT_MUSIC_PAYLOAD_STRING.format(query=q),
headers=headers)
return await response.json()

Objective

Extract search results & music tracks from raw json to python List of dictionaries

Wanted/Required data

  • title
  • videoId
  • author
  • duration

Starting point

  • Clone repo & change directory & Install development
pip install .
  • Get yt_music_key

    • Open music.youtube.com & search something,
    • Open network, & look for the search request, use the key parameter value as yt_music_key
  • Raw Json

from ytpy import YoutubeClient
import asyncio
import aiohttp


async def main(loop):
    session = aiohttp.ClientSession()

    client = YoutubeClient(session, yt_music_key="<youtube-music-key>")

    response = await client.search_music(q='black suit')

    # Response is a raw json
    print(response)

    await session.close()


loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
  • Start parsing

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.