You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium实现TikTok扫码登录失败:URL显示undefined

TikTok扫码登录出现undefined问题的解决办法

1. 先修复代码里的语法错误

你最后一行执行JS的代码有明显语法问题:

document.querySelector("a[href*=qrcode]".click();

这里少了一个闭合的),正确写法应该是:

document.querySelector("a[href*=qrcode]").click();

语法错误会导致JS执行失败,直接打断登录流程,这是出现undefined提示的首要原因。

2. 替换硬编码sleep为显式等待

固定的sleep()不可靠,页面加载速度受网络影响,很可能出现元素还没加载就执行点击操作的情况。改用Selenium的显式等待,等元素可点击后再操作,稳定性更高。

3. 修正后的完整代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options

if __name__ == "__main__":
    # 配置浏览器参数,规避TikTok的反爬检测
    options = Options()
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36')

    driver = webdriver.Chrome(options=options)
    wait = WebDriverWait(driver, 10)  # 最多等待10秒

    driver.get("https://www.tiktok.com")

    # 等待顶部登录按钮加载完成并点击
    login_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[data-e2e=nav-login-button]")))
    login_btn.click()

    # 等待扫码登录按钮加载完成并点击
    qrcode_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href*=qrcode]")))
    qrcode_btn.click()

    # 等待用户扫码完成,可根据实际情况调整等待时间,或后续判断登录状态
    driver.implicitly_wait(160)
    driver.quit()

4. 额外注意事项

如果修正后仍出现undefined提示,大概率是TikTok检测到了Selenium的自动化特征,上面代码里已经添加了规避检测的浏览器参数,要是还不行,可以尝试:

  • 更换用户代理为当前真实浏览器的UA
  • 给浏览器添加常用扩展(如AdBlock)模拟正常用户环境
  • 避免频繁运行脚本,减少被风控的概率

内容的提问来源于stack exchange,提问作者Dori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:22:44