4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TikTokのAPIを利用してトレンドのユーザーを取得してみた!

Posted at

こちらの非公式APIを利用すれば色々できるみたいなので、試しに使ってみました!
仕組みはどうやらPythonでスクレイピングしているようです。

git cloneしてリポジトリをローカルに落としてきます。
使い方は基本的にread meに書いてます。

しかし、read meの通りにやってもエラーになります。
そこで自分が行ったこと。

requests
playwright

こちら二つのライブラリをインストール
requestsは初期から入っているかもです。
playwrightはPythonのスクレイピングのライブラリのようです。

普通にやってもエラーになるので、cookieを取得して保存し、それを読み取るようにします。

KeyError: "name='ttwid', domain=None, path=None"

それでもこんな感じのエラーが発生しました。

かなりハマりましたが、issueに解決策が載っていました

参考

どうやらheadというリクエストは使えないようなので、requests.getに変更し、
headersに自分のブラウザのUser-Agentを追加します。

user-agentはこのサイトとかから確認できます
https://testpage.jp/tool/ip_user_agent.php

        spawn = requests.get(
            "https://www.tiktok.com",
            proxies=Trending.parent._format_proxy(processed.proxy),
            **Trending.parent._requests_extra_kwargs,
            headers={
                'User-Agent': "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
            }
        )

成功したコード

from TikTokApi import TikTokApi
import json

# read data from json file, cookie exported from webbrowser
def get_cookies_from_file():
    with open('exported-cookies.json') as f:
        cookies = json.load(f)

    cookies_kv = {} # key-value
    for cookie in cookies:
        cookies_kv[ cookie['name'] ] = cookie['value']
        print ( cookie['name'] + "=" + cookie['value'] )

    return cookies_kv


print('Reading data from cookie file...')
cookies = get_cookies_from_file() #obtiene un dictionary key-value

def get_cookies(**kwargs):
    return cookies

api = TikTokApi()

api._get_cookies = get_cookies 

print("    Requesting data from TikTok")
for video in api.trending.videos():
    print ( video.author.username)

出力結果

スクリーンショット 2023-01-30 22.43.30.png

これはトレンドの投稿のユーザーIDを出力しています。

ビデオの情報を取得

from TikTokApi import TikTokApi
import json

# read data from json file, cookie exported from webbrowser
def get_cookies_from_file():
    with open('exported-cookies.json') as f:
        cookies = json.load(f)

    cookies_kv = {} # key-value
    for cookie in cookies:
        cookies_kv[ cookie['name'] ] = cookie['value']
        print ( cookie['name'] + "=" + cookie['value'] )

    return cookies_kv


print('Reading data from cookie file...')
cookies = get_cookies_from_file() #obtiene un dictionary key-value

def get_cookies(**kwargs):
    return cookies

api = TikTokApi()

api._get_cookies = get_cookies 

print("    Requesting data from TikTok")
video = api.video(id="ビデオID")
# for video in api.trending.videos():
print ( video.info_full() )

出力結果

{
  "extra": {
      "fatal_item_ids": [],
      "logid": "xx",
      "now": xx
  },
  "itemInfo": {
      "itemStruct": {
          "author": {
              "avatarLarger": "xx",
              "avatarMedium": "xx",
              "avatarThumb": "xx",
              "commentSetting": 0,
              "duetSetting": 0,
              "ftc": False,
              "id": "xx",
              "isADVirtual": False,
              "nickname": "xx",
              "openFavorite": False,
              "privateAccount": False,
              "relation": 0,
              "secUid": "xx",
              "secret": False,
              "signature": "xxx",
              "stitchSetting": 0,
              "uniqueId": "yuri_glitter_comp",
              "verified": False
          },
          "challenges": [{
              "coverLarger": "",
              "coverMedium": "",
              "coverThumb": "",
              "desc": "",
              "id": "xx",
              "profileLarger": "",
              "profileMedium": "",
              "profileThumb": "",
              "title": "xx"
          }, {
              "coverLarger": "",
              "coverMedium": "",
              "coverThumb": "",
              "desc": "",
              "id": "xx",
              "profileLarger": "",
              "profileMedium": "",
              "profileThumb": "",
              "title": "xx"
          }, {
              "coverLarger": "",
              "coverMedium": "",
              "coverThumb": "",
              "desc": "",
              "id": "5456468",
              "profileLarger": "",
              "profileMedium": "",
              "profileThumb": "",
              "title": "xx"
          }],
          "createTime": x,
          "desc": "xx ",
          "digged": False,
          "duetDisplay": 0,
          "duetEnabled": True,
          "forFriend": False,
          "id": "xx",
          "itemCommentStatus": 0,
          "music": {
              "authorName": "xx",
              "coverLarge": "https:xx",
              "coverMedium": "xx",
              "coverThumb": "xx",
              "duration": 54,
              "id": "xx",
              "original": False,
              "playUrl": "xx",
              "title": "xx"
          },
          "officalItem": False,
          "originalItem": False,
          "privateItem": False,
          "secret": False,
          "shareEnabled": True,
          "stats": {
              "commentCount": 1,
              "diggCount": 10,
              "playCount": 10,
              "shareCount": 1
          },
          "stitchDisplay": 0,
          "stitchEnabled": True,
          "textExtra": [{
              "awemeId": "",
              "end": 11,
              "hashtagId": "xx4",
              "hashtagName": "xx",
              "isCommerce": False,
              "start": 8,
              "subType": 0,
              "type": 1
          }, {
              "awemeId": "",
              "end": 16,
              "hashtagId": "xx",
              "hashtagName": "xx",
              "isCommerce": False,
              "start": 12,
              "subType": 0,
              "type": 1
          }, {
              "awemeId": "",
              "end": 25,
              "hashtagId": "xx",
              "hashtagName": "xx",
              "isCommerce": False,
              "start": 17,
              "subType": 0,
              "type": 1
          }],
          "video": {
              "bitrate": 1296321,
              "bitrateInfo": [{
                  "Bitrate": xx,
                  "CodecType": "h264",
                  "GearName": "normal_720_0",
                  "PlayAddr": {
                      "DataSize": xx,
                      "FileCs": "xx",
                      "FileHash": "xx",
                      "Uri": "xx",
                      "UrlKey": "xx",
                      "UrlList": ["xx", "xx"]
                  },
                  "QualityType": 10
              }],
              "codecType": "h264",
              "cover": "xx",
              "definition": "720p",
              "downloadAddr": "xx",
              "duration": 54,
              "dynamicCover": "xxx",
              "encodeUserTag": "",
              "encodedType": "normal",
              "format": "mp4",
              "height": 1024,
              "id": "7xx",
              "originCover": "hxx",
              "playAddr": "xxx",
              "ratio": "720p",
              "videoQuality": "normal",
              "volumeInfo": {
                  "Loudness": -10.8,
                  "Peak": 1
              },
              "width": 576,
              "zoomCover": {
                  "240": "xx",
                  "480": "xx",
                  "720": "xxx",
                  "960": "xx"
              }
          }
      }
  },
  "log_pb": {
      "impr_id": "xxx"
  },
  "statusCode": 0,
  "status_code": 0
}

実際にデータが入っているところはxxで伏せてます。

こちらでユーザーの情報を取得するコードも試してみたのですが、上手くいきませんでした

proxyとcustom_verify_fp両方試してみたのですが、成功しませんでした。

誰かuserInfoを取得する方法を知っていたら教えてください。

とはいえビデオの情報やtrendの情報は取得できました!

apiを見てみると、そのほかにも

  • コメント
  • 検索結果
  • 音楽
  • ハッシュタグ

などが取得できるようなので、何かサービスを作ってみようと思っているのですが、どんな情報に価値があるのかわからず、何を作るか考え中です。

こんなサービス欲しい!とかアイデアがあれば教えてください。

最後に

ほかにもTikTokのAPIを提供しているサービスはたくさんあるみたいなので、それを使うとほかにも色々取得できるかもです!

4
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?