> **合规声明**:抖音没有公开面向普通用户的“自动关注”API。网页版自动关注本质上是用 Selenium/Playwright 模拟人工点击,属于平台规则高风险操作,可能导致限流、功能限制甚至封号。本文仅用于学习浏览器自动化、个人测试和自动化脚本编写,**不要用于批量涨粉、营销骚扰、刷量、代运营等违规场景**。脚本内置每日上限、随机延迟、手动登录和日志记录,遇到验证码请手动处理,不要尝试绕过风控。
## 一、原理简述
自动关注脚本通常由四部分组成:
1. **浏览器自动化**:用 Selenium 驱动 Chrome 打开抖音网页版。
2. **手动登录**:脚本不保存账号密码,第一次运行时由你本人在弹出的浏览器中登录。
3. **搜索用户列表**:打开 `https://www.douyin.com/search/关键词?type=user`。
4. **模拟点击关注**:找到页面上的“关注”按钮,判断是否为“已关注”,然后点击,并加入随机等待和每日次数限制。
抖音网页版页面结构会变化,所以代码里的 CSS 选择器只是示例。实际运行时如果找不到按钮,需要按 F12 打开开发者工具,重新确认选择器。
## 二、环境配置教程
### 1. 安装 Python
建议使用 Python 3.10 或 3.11。安装时 Windows 用户记得勾选 `Add Python to PATH`。
检查版本:
```bash
python --version
```
macOS/Linux 可用:
```bash
python3 --version
```
### 2. 安装 Chrome 浏览器
安装最新版 Google Chrome。脚本会通过 `webdriver-manager` 自动下载匹配的 ChromeDriver;如果自动下载失败,可以手动去 ChromeDriver 官网下载对应版本,并配置到环境变量。
### 3. 创建虚拟环境
在项目目录下执行:
Windows:
```bash
python -m venv venv
venv\Scripts\activate
```
macOS/Linux:
```bash
python3 -m venv venv
source venv/bin/activate
```
### 4. 安装依赖
创建 `requirements.txt`:
```txt
selenium>=4.20.0
webdriver-manager>=4.0.1
```
安装:
```bash
pip install -r requirements.txt
```
### 5. 项目目录建议
```text
douyin_auto_follow/
├── douyin_auto_follow.py
├── requirements.txt
├── chrome_profile/ # 自动生成,保存浏览器登录状态
├── follow_state.json # 自动生成,记录每日关注次数
└── auto_follow.log # 自动生成,运行日志
```
## 三、完整代码
新建 `douyin_auto_follow.py`,写入以下代码:
```python
# -*- coding: utf-8 -*-
"""
抖音网页版自动关注演示脚本
仅用于学习浏览器自动化,请遵守平台规则。
"""
import hashlib
import json
import logging
import random
import sys
import time
from datetime import datetime
from pathlib import Path
from urllib.parse import quote
from selenium import webdriver
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
WebDriverException,
)
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
BASE_DIR = Path(__file__).resolve().parent
PROFILE_DIR = BASE_DIR / "chrome_profile"
STATE_FILE = BASE_DIR / "follow_state.json"
LOG_FILE = BASE_DIR / "auto_follow.log"
# ===== 可配置参数 =====
SEARCH_KEYWORD = "美食" # 搜索关键词
DAILY_LIMIT = 10 # 每日最多关注数,建议调小
MIN_DELAY = 4.0 # 最小随机等待秒数
MAX_DELAY = 9.0 # 最大随机等待秒数
MAX_SCROLLS = 5 # 最多滚动加载轮数
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler(LOG_FILE, encoding="utf-8"),
logging.StreamHandler(sys.stdout),
],
)
logger = logging.getLogger("douyin_auto_follow")
def today_str():
return datetime.now().strftime("%Y-%m-%d")
def load_state():
if STATE_FILE.exists():
try:
return json.loads(STATE_FILE.read_text(encoding="utf-8"))
except Exception:
pass
return {"date": today_str(), "count": 0, "followed": []}
def save_state(state):
if state.get("date") != today_str():
state["date"] = today_str()
state["count"] = 0
state["followed"] = []
STATE_FILE.write_text(
json.dumps(state, ensure_ascii=False, indent=2),
encoding="utf-8",
)
def human_sleep(a=MIN_DELAY, b=MAX_DELAY):
time.sleep(random.uniform(a, b))
def create_driver():
PROFILE_DIR.mkdir(exist_ok=True)
options = Options()
options.add_argument("--start-maximized")
options.add_argument("--disable-gpu")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument(f"--user-data-dir={PROFILE_DIR}")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
driver = webdriver.Chrome(
service=Service(ChromeDriverManager().install()),
options=options,
)
# 仅用于减少自动化特征误报,不用于绕过验证码或风控
driver.execute_cdp_cmd(
"Page.addScriptToEvaluateOnNewDocument",
{
"source": "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
},
)
return driver
def wait_login(driver):
driver.get("https://www.douyin.com/")
logger.info("请在弹出的 Chrome 窗口中手动登录抖音。")
input("登录完成并看到首页后,按回车继续...")
WebDriverWait(driver, 20).until(
lambda d: "douyin.com" in d.current_url
)
def open_search(driver, keyword):
url = f"https://www.douyin.com/search/{quote(keyword)}?type=user"
logger.info("打开搜索页:%s", url)
driver.get(url)
human_sleep(2, 4)
def get_follow_buttons(driver):
selectors = [
"div[data-e2e='user-card'] button",
"div[class*='userCard'] button",
"div[class*='user-card'] button",
"div[class*='UserCard'] button",
]
for selector in selectors:
try:
buttons = driver.find_elements(By.CSS_SELECTOR, selector)
if buttons:
return buttons
except WebDriverException:
continue
# 兜底:查找文本包含“关注”的按钮
return driver.find_elements(
By.XPATH,
"//button[contains(normalize-space(.), '关注')]",
)
def button_fingerprint(button):
try:
html = button.get_attribute("outerHTML") or ""
except StaleElementReferenceException:
return ""
return hashlib.md5(html.encode("utf-8", errors="ignore")).hexdigest()
def try_follow_once(driver, state):
buttons = get_follow_buttons(driver)
logger.info("当前页面找到 %d 个候选按钮", len(buttons))
for button in buttons:
if state["count"] >= DAILY_LIMIT:
logger.info("已达到每日上限 %d,停止。", DAILY_LIMIT)
return False
try:
text = (button.text or "").strip()
if "已关注" in text or "互相关注" in text:
continue
if "关注" not in text:
continue
fp = button_fingerprint(button)
if fp and fp in state["followed"]:
continue
card_text = ""
try:
card_text = button.find_element(
By.XPATH,
"./ancestor::div[contains(@class,'user')][1]",
).text
except Exception:
card_text = text
if "我的主页" in card_text or "编辑资料" in card_text:
logger.info("跳过疑似自己的卡片")
continue
logger.info("准备关注:%s", card_text.replace("\n", " | ")[:120])
button.click()
state["count"] += 1
if fp:
state["followed"].append(fp)
save_state(state)
logger.info(
"关注成功,今日累计 %d/%d",
state["count"],
DAILY_LIMIT,
)
human_sleep()
return True
except (
StaleElementReferenceException,
NoSuchElementException,
WebDriverException,
) as exc:
logger.warning("处理按钮失败:%s", exc)
human_sleep(1, 2)
return False
def scroll_page(driver):
driver.execute_script("window.scrollBy(0, 900);")
human_sleep(1.5, 3.0)
def main():
state = load_state()
save_state(state)
driver = None
try:
driver = create_driver()
wait_login(driver)
open_search(driver, SEARCH_KEYWORD)
human_sleep(2, 4)
for i in range(MAX_SCROLLS):
logger.info("第 %d 轮扫描", i + 1)
if not try_follow_once(driver, state):
logger.info("本轮没有可关注对象,尝试滚动加载更多。")
if state["count"] >= DAILY_LIMIT:
break
scroll_page(driver)
logger.info(
"任务结束:今日关注 %d 个,上限 %d。",
state["count"],
DAILY_LIMIT,
)
except KeyboardInterrupt:
logger.info("用户中断")
except Exception:
logger.exception("运行出错")
finally:
if driver:
driver.quit()
if __name__ == "__main__":
main()
```
## 四、代码关键点讲解
1. **`create_driver()`**:创建 Chrome 浏览器,使用 `chrome_profile` 目录保存登录状态。第一次需要手动登录,后续如果目录没被删除,通常可以复用登录状态。
2. **`wait_login()`**:脚本不会自动输入账号密码,而是等你手动登录后按回车继续。这样更安全。
3. **`get_follow_buttons()`**:尝试多种 CSS 选择器,最后用 XPath 查找文本包含“关注”的按钮。抖音页面改版后,这里可能需要调整。
4. **`try_follow_once()`**:跳过“已关注”“互相关注”,用按钮 HTML 指纹避免重复关注,并加入随机等待。
5. **`DAILY_LIMIT`**:每日关注上限,默认 10。演示时建议设置更小,例如 3~5。
6. **`follow_state.json`**:记录日期、当天次数和已处理按钮指纹,避免重复操作。
7. **`auto_follow.log`**:记录运行过程,方便排查选择器失效、登录失败等问题。
## 五、运行步骤
1. 安装依赖。
2. 修改代码顶部的 `SEARCH_KEYWORD` 和 `DAILY_LIMIT`。
3. 在终端运行:
```bash
python douyin_auto_follow.py
```
4. 浏览器弹出后,手动登录抖音。
5. 回到终端按回车。
6. 脚本会自动打开搜索页并尝试关注。
7. 运行结束后查看 `auto_follow.log` 和 `follow_state.json`。
## 六、常见问题
- **ChromeDriver 版本不匹配**:`webdriver-manager` 一般会自动处理;失败时手动下载对应版本。
- **Chrome 已打开导致 `user-data-dir` 报错**:关闭所有 Chrome 进程,或删除 `chrome_profile` 后重新登录。
- **找不到关注按钮**:抖音页面结构变化,按 F12 检查真实 DOM,修改 `get_follow_buttons()` 里的选择器。
- **出现验证码或安全验证**:停止脚本,手动处理,不要尝试绕过。
- **账号被限制**:立即停止,降低频率,遵守平台规则。
## 七、合规替代方案
如果目的是做抖音运营或涨粉,更稳妥的方式是:
1. 使用抖音官方开放平台、企业号后台或巨量引擎等合规工具。
2. 通过优质内容、直播互动、评论区运营、粉丝群等方式自然增长。
3. 使用官方广告投放,而不是模拟点击。
4. 遵守《抖音用户服务协议》和《网络信息内容生态治理规定》等法律法规。
总结:自动关注脚本可以作为 Python 浏览器自动化练习,但不要把它用于违规涨粉或批量营销。真正可持续的运营,仍然要依靠内容、合规工具和真实互动。
0 条评论
还没有评论,来说两句吧~
评论已关闭