davidteather / TikTok-Api

The Unofficial TikTok API Wrapper In Python
https://davidteather.github.io/TikTok-Api
MIT License
4.91k stars 984 forks source link

NotImplementedError using video.bytes() #1167

Open frackz opened 5 months ago

frackz commented 5 months ago

Hi so i am trying to download a bunch of videoes quick, but the video.bytes function does not work. And by the name i would think it was because of it not working because of TikTok updates, but i just wanted to check in and see if this was the case.

mitramir55 commented 4 months ago

Same issue. I want to download videos related to one specific hashtag. So firstly, I used the hashtag example and added the video bytes extraction for downloading the video. I kept getting 'Not Implemented' errors. I see that this function has not been written completely on GitHub. Here is my code:


from TikTokApi import TikTokApi
import asyncio
import os
import json

DIR = r'...'
VIDEO_DIR = f"..."

# Set the ms_token directly in the notebook
os.environ['ms_token'] = "my_token"
HASHTAG = 'bacon'

ms_token = os.environ.get("ms_token", None) 

async def get_hashtag_videos():
    videos_dicts = []
    all_ids = []

    videos_bytes_list = []
    async with TikTokApi() as api:
        await api.create_sessions(ms_tokens=[ms_token], num_sessions=1, sleep_after=3)
        tag = api.hashtag(name=f"{HASHTAG}")
        async for vid in tag.videos(count=3):

            vid_dict = vid.as_dict
            videos_dicts.append(vid_dict)

            id = vid_dict['id']
            all_ids.append(id)

            vid_bytes = await vid.bytes()
            print(vid_bytes)
            videos_bytes_list.append(vid_bytes)

    # writing the videos
    for (v, id) in zip(videos_bytes_list, all_ids):
        with open(f"{VIDEO_DIR}\\video_{id}.mp4", 'wb') as out:
            out.write(v)

    # Save videos to a JSON file
    with open(f'tiktok_videos_{HASHTAG}_July_19.json', 'w') as f:
        json.dump(videos_dicts, f, indent=4)

if __name__ == "__main__":
    asyncio.run(get_hashtag_videos())
    print("Videos saved successfully to 'tiktok_videos.json'")

I also try to understand if I can make a request for several hashtags with the "|" symbol. @davidteather Please let me know if I can help in developing the code or if you're working on it already.

Thanks.

mitramir55 commented 4 months ago

An update: if you look into the dictionary object of the video, you see 'video' -> 'bitrateInfo'-> 'PlayAddr' -> 'UrlList'

The last link in this list can be used for downloading the videos. So after getting the dictionary of videos you need (video.as_dict) you can download the videos.

This is how I did it:

import pandas as pd
df = pd.read_json(r"...\tiktok_videos_bacon.json")

# get the id and url
df.loc[:, 'video_id'] = df.loc[:, 'video'].apply(lambda x: x['id'])
df.loc[:, 'url'] = df.loc[:, 'video'].apply(lambda x: x['bitrateInfo'][0]['PlayAddr']['UrlList'][-1])

# download the videos
import requests

def download_vid(video_url, id):
    # Send a GET request to the URL
    response = requests.get(video_url)

    # Check if the request was successful
    if response.status_code == 200:
        # Open a file in binary write mode
        with open(f'tiktok_video_{id}.mp4', 'wb') as file:
            # Write the content of the response to the file
            file.write(response.content)
        print('Video downloaded successfully!')
    else:
        print('Failed to download video. Status code:', response.status_code)

for (id, video_url) in zip(df.loc[:, 'id'].values, df.loc[:, 'url']):
    download_vid(video_url, id)
bendavidsteel commented 4 months ago

This PR fixes this issue: #1174 , feel free to pull the branch in the meantime