TikTok-Api: [BUG] - KeyError

Code:

from TikTokApi import TikTokApi
api = TikTokApi()
for video in api.trending.videos():
    print(video.as_dict)

Error:

Traceback (most recent call last):
  File "d:\TikTok\TikTok ID Samples.py", line 3, in <module>
    for video in api.trending.videos():
  File "C:\Users\fun64\AppData\Local\Programs\Python\Python310\lib\site-packages\TikTokApi\api\trending.py", line 40, in videos
    ttwid = spawn.cookies["ttwid"]
  File "C:\Users\fun64\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\cookies.py", line 334, in __getitem__
    return self._find_no_duplicates(name)
  File "C:\Users\fun64\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\cookies.py", line 413, in _find_no_duplicates
    raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
KeyError: "name='ttwid', domain=None, path=None"

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 14
  • Comments: 23 (1 by maintainers)

Most upvoted comments

Hey everyone! I managed to get a fix (hopefully it works to others). I changed C:\Users\user\AppData\Local\Programs\Python\Python310\Lib\site-packages\TikTokApi\api\search.py for this.

You change…

spawn = requests.head(
    "https://www.tiktok.com",
    proxies=Search.parent._format_proxy(processed.proxy),
    **Search.parent._requests_extra_kwargs
)
ttwid = spawn.cookies["ttwid"]

to…

spawn = requests.get(
    "https://www.tiktok.com",
    proxies=Search.parent._format_proxy(processed.proxy),
    **Search.parent._requests_extra_kwargs,
    headers={
        'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5"
    }
)
ttwid = spawn.cookies.get_dict()["ttwid"]

Basically, I changed the request type from HEAD to GET, and added a User-Agent. I compiled all the answers I found from trying to fix this error, so technically this piece of work was a team effort.

Quick notice: Some other python files still have that old code. So just replace that old code with the new one. If it still errors, try to get some common sense and maybe you can fix it.

I think I can solve this problem by logging into tiktok and importing the cookie https://github.com/davidteather/TikTok-Api/issues/891#issuecomment-1148930488

Same error here. V5.2.2