抖音助播程序python实现,可以自动评论,批量发布带节奏文字

news/2025/2/27 14:45:46/文章来源:https://www.cnblogs.com/lambertlt/p/18740926

chrome测试版本浏览器,下载地址

"""
Version: 1.0
Autor: Lambert_work@163.com
Date: 2025-02-25 10:21:12
LastEditors: lambertlt lambert_Y_Y@163.com
LastEditTime: 2025-02-25 10:21:25
"""from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from fake_useragent import UserAgent
from selenium.webdriver.common.action_chains import ActionChains
from requests.exceptions import Timeout, RequestException
import time
import re
import pickle
import pyautogui
import random
import requests
from playsound import playsound# 直播链接
live_url = "https://live.douyin.com/540517338200"
comment_box_class = "webcast-chatroom___textarea"
list_person = []
# 欢迎新人开始时间
hello_new_person_start_time = 0
# 循环时间间隔s
t = 0.5
# 欢迎新人的频率s
hello_new_person_frequency = 5
# 特殊字符
chars = [".", "。", "!", "!", "、", "`", "·", "~", "~", "_", "__", ";", ";"]
# 上次的姓名
last_time_name = ""
# 评论列表
comment_list = []
last_comment = ""
# 自动回复列表 第一项为匹配关键词,后面的为回复内容
auto_reply_list = [["3","这款儿童奶瓶刷轻量便携:出行无忧,随时随地都能使用","硅胶刷毛:柔软设计,清洁无死角","多功能配件:包含多种刷具,全面清洁","快速开合:1秒轻松开启,高效清洗","小巧收纳:小巧设计,轻松存放出门",],["2","这款儿童马桶坐便器能为您的小宝贝带来舒适与安全的如厕体验","专为幼儿设计,这款坐便器拥有恰到好处的高度和尺寸,确保您的孩子能够轻松、独立地使用","采用环保材料制成,表面光滑易于清洁,同时配备防滑底部,保障孩子在使用过程中的稳定性与安全性","简洁而不失可爱的外观设计,可以轻松融入您家的卫生间环境",],["1","这款儿童凉拖鞋卡通可爱:立体卡通鞋面,萌趣十足","而且有防滑设计:强抓地力,行走稳健","设计轻盈舒适:环保EVA材质,贴合脚型","后跟带设计:轻松切换,便捷活动","适合夏季:专为儿童设计,清凉舒适",],["退换货有保障吗", "都是支持7天无理由退货的宝子们"],
]
auto_send_start_time = 0
# 自动发送带节奏评论的时间间隔
auto_send_frequency = 120
auto_send_list = ["儿童助眠直播间,这里有数不清的童话故事","家里有孩子正好要休息的可以在直播间听一听童话故事!","如果需要儿童故事电子资料,下方小车,任意下.单,四信息即可德到",
]
auto_send_list1 = ["直播间的朋友们需要介绍凉拖鞋的扣:1","直播间的朋友们需要介绍儿童马桶的扣:2","直播间的朋友们需要介绍奶瓶刷的扣:3",
]
is_typing = False# 主函数
def main_douyin():driver = douyin_login()input("登陆成功后,点击回车键继续")update_cookies(driver)operating(driver)driver.quit()# 操作
def operating(driver):global hello_new_person_start_time, auto_send_start_timetime.sleep(2)driver.get(live_url)time.sleep(5)pyautogui.press("p")input("点击回车键开始助播程序")send_comment(driver, "直播助手进入直播间...")hello_new_person_start_time = int(time.time())auto_send_start_time = int(time.time())while True:get_new_notice(driver)hello_new_person(driver)get_new_comment(driver)auto_send_comment(driver)time.sleep(t)# 自动发送带节奏评论
def auto_send_comment(driver):global auto_send_start_time, auto_send_frequencynow_time = int(time.time())if now_time - auto_send_start_time > auto_send_frequency:if is_typing == True:while True:time.sleep(0.5)if is_typing == False:breakfor i in auto_send_list:send_comment(driver, i)auto_send_start_time = int(time.time())# 获取新评论
def get_new_comment(driver):global last_comment, comment_listelement_list = driver.find_elements(By.CLASS_NAME, "webcast-chatroom___content-with-emoji-text")if (len(element_list) > 0and element_list[len(element_list) - 1].text != last_commentand is_in_second_values(element_list[len(element_list) - 1].text)):comment = element_list[len(element_list) - 1].textcomment_list.append(comment)last_comment = commentprint("新评论:", comment)handle_comment(driver)# 判断s是否在字典的value中,存在返回false
def is_in_second_values(s):global auto_reply_listfor item in auto_reply_list:for i in range(1, len(item)):if item[i] == s:return Falsefor n in auto_send_list:if n == s:return Falsereturn True# 处理评论
def handle_comment(driver):global comment_list, is_typingif len(comment_list) > 0:for item in comment_list:index = 0for p in auto_reply_list:pattern = re.compile(re.escape(p[0]))matched_strings = pattern.findall(item)if len(matched_strings) > 0:print("匹配结果:", matched_strings)if is_typing == True:time.sleep(1)n = len(auto_reply_list[index])for i in range(1, n):if is_typing == True:while True:time.sleep(0.5)if is_typing == False:breaksend_comment(driver, auto_reply_list[index][i])try:comment_list.remove(item)except:passindex += 1comment_list.clear()# 获取新信息
def get_new_notice(driver):global last_time_nameelement = driver.find_element(By.CLASS_NAME, "webcast-chatroom___bottom-message")element_text = element.textsplit = element_text.split(" ")if last_time_name == element_text:returnelif len(split) > 1 and split[1] == "为主播点赞了":playsound('./audio/觉得主播给力的,帮忙分享一下直播间,让更多朋友来抢福利!.wav')returnelif len(split) > 1 and split[1] == "来了":print("------", split)name = filter_special_chars(split[0])if len(list_person) > 5:temp = list_person[len(list_person) - 1]list_person.clear()list_person.append(temp)list_person.append(name)last_time_name = element_text# 欢迎新人
def hello_new_person(driver):global hello_new_person_start_timenow_time = int(time.time())if now_time - hello_new_person_start_time >= hello_new_person_frequency:if len(list_person) > 0:random.shuffle(chars)text = ("欢迎:"+ '"'+ list_person[0]+ ' " 进入直播间!'+ random.choice(chars))if is_typing == True:while True:time.sleep(0.5)if is_typing == False:breaksend_comment(driver, text)print(text)list_person.pop(0)hello_new_person_start_time = int(time.time())#  发送评论内容
def send_comment(driver, comment):global is_typingis_typing = Trueelement = driver.find_element(By.CLASS_NAME, comment_box_class)click_element(driver, element)type_character(element, comment)pyautogui.press("enter")is_typing = False# 点击元素
def click_element(driver, element):action = ActionChains(driver)action.move_to_element(element).click().perform()time.sleep(1)# 打字输入
def type_character(element, text):for char in text:wait_time = random.uniform(0.09, 0.3)element.send_keys(char)time.sleep(wait_time)# 过滤掉字符串中的特殊字符和表情符号,只保留汉字、英文字母、数字和常见标点符号
def filter_special_chars(text):# 正则表达式模式,匹配汉字、英文字母、数字和常见标点符号pattern = r"[^\w\u4e00-\u9fff\s\.\,\!\?\;\:\-$$]"# \w 匹配字母数字下划线,\u4e00-\u9fff 匹配汉字,其他为常见标点符号if text == "":return ""# 使用 sub 函数替换掉所有不匹配该模式的字符为空格result = re.sub(pattern, "", text)# 移除多余的空格,使输出更加整洁result = re.sub(r"\s+", " ", result).strip()if result == "":return "表情用户"return result# 打开抖音进行登陆
def douyin_login():chrome_options = Options()set_options(chrome_options)# service = Service(ChromeDriverManager().install())service = Service(executable_path="./chromedriver-mac-arm64/chromedriver")driver = webdriver.Chrome(service=service, options=chrome_options)driver.set_window_size(1483, 1080)driver.get("https://www.baidu.com/")script = """var his = ['百度。https://www.baidu.com/','百度搜索hello。https://www.baidu.com/s?ie=UTF-&wd=hello','百度搜索抖音。https://www.baidu.com/s?ie=UTF-8&wd=抖音'];
his.forEach(item =>{let [title, url]=item.split('。');document.title=title;history.pushState({}, '', url);});"""driver.execute_script(script)time.sleep(1)driver.get("https://www.douyin.com/")script = """var his = ['抖音。https://www.douyin.com/?recommend=1','抖音记录美好生活。https://www.douyin.com/follow','我的抖音。https://www.douyin.com/user/self?from_tab_name=main&showTab=like'];
his.forEach(item =>{let [title, url]=item.split('。');document.title=title;history.pushState({}, '', url);});"""driver.execute_script(script)load_cookies(driver)pyautogui.press("down")return driver# 保存 Cookie
def save_cookies(driver, filename="/Users/lantian/shell/python/douyin_cookies.pkl"):input("请手动登录后按回车键继续...")with open(filename, "wb") as file:pickle.dump(driver.get_cookies(), file)print(f"Cookie 已保存到 {filename}")def update_cookies(driver, filename="/Users/lantian/shell/python/douyin_cookies.pkl"):with open(filename, "wb") as file:pickle.dump(driver.get_cookies(), file)print(f"Cookie 已更新 {filename}")# 加载Cookie
def load_cookies(driver, filename="/Users/lantian/shell/python/douyin_cookies.pkl"):cookies = pickle.load(open(filename, "rb"))for cookie in cookies:driver.add_cookie(cookie)driver.refresh()time.sleep(2)# 配置浏览器
def set_options(chrome_options):ua = UserAgent()s = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36"# 指定 Chrome 用户配置文件路径user_data_dir = "/Users/lantian/Library/Application Support/Google/Chrome"profile_directory = "/Users/lantian/Library/Application Support/Google/Chrome/Default"  # 替换为你的配置文件目录chrome_options = webdriver.ChromeOptions()chrome_options.add_argument(f"--user-data-dir={user_data_dir}")chrome_options.add_argument(f"--profile-directory={profile_directory}")chrome_options.add_argument("--disable-gpu")chrome_options.add_argument(f"user-agent={s}")chrome_options.add_argument("--disable-blink-features=AutomationControlled")chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])chrome_options.add_experimental_option("useAutomationExtension", False)chrome_options.add_argument("--disable-extensions")# 设置浏览器指纹chrome_options.add_argument("--disable-infobars")chrome_options.add_argument("--disable-dev-shm-usage")chrome_options.add_argument("--no-sandbox")chrome_options.add_argument("--remote-debugging-port=9222")# 获取数据
def fetch_data(url):try:# 发送 GET 请求,并设置超时时间为 5 秒response = requests.get(url, timeout=5)# 检查响应状态码if response.status_code == 200:# 将响应内容解析为 JSON 格式data = response.json()return dataelse:print(f"请求失败,状态码: {response.status_code}")return Noneexcept Timeout:print("请求超时")return Noneexcept RequestException as e:print(f"请求发生错误: {e}")return None# 运行主函数
main_douyin()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/890636.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vscode中不同项目使用不用的nodejs版本

只需要在vscode中当前项目里面增加一个设置

低代码在项目管理中的5大实战案例:不懂代码也能快速搭建系统!

作为项目管理领域的“老司机”,我见过太多团队因传统开发效率低、需求响应慢而错失机会。低代码平台的崛起,让业务人员也能快速搭建系统,大幅缩短交付周期。以下是5个典型场景的实践案例,用最通俗的语言讲透核心逻辑👇案例1:3天上线CRM系统(客户关系管理) 背景:某销售…

[字符串算法]Manacher

我将永远追随六花的脚步1.前置知识 回文子串  回文的子串 最长回文子串  字符串中最长的回文子串 回文半径  设以\(i\)为中心的最大回文子串的长度为\(n\),则这个字符串第\(i\)位的回文半径为\((n+1)/2\) 2.算法流程 2.1 预处理 在处理回文子串(马拉车算法适用)的问题时…

[数据结构]树

我最喜欢六花了树(基础) 1 定义 1.1 树是什么 树是一种数据结构,因为形似倒着的树而得名. 树是一种特殊图 1.2 树的定义 递归定义 1.2.1 有根树的定义 形象化的,如图1,有根树存在根节点这一定义,从根节点可以分出任意个分支,这任意个分支又可以继续细分,分出的节点称…

StrokesPlus【电脑鼠标键盘手势软件】v0.5.8.0 中文绿色便携版

点击上方蓝字关注我 前言 StrokesPlus.net是一个超方便的手势识别软件,它能帮你用手势来代替鼠标和键盘操作。用起来既简单又灵活,功能还特别强大。 操作起来非常简单,它有好多实用的功能,比如智能识别你写的字、设定手势操作的区域、模拟鼠标的各种动作、运行脚本、响应窗…

大模型推理主战场:什么才是通信协议标配?

关键词:# DeepSeek ;# SSE ;# WebSocketSSE 和 WebSocket 是什么? 大模型应用出现前的主流网络通信协议是什么? 为什么大模型应用没有沿用 Web 类应用的主流通信协议? 为什么 SSE 和 WebSocket 更适合支持大模型应用? 实时通信协议的技术挑战和应对方案 Whats Next?Dee…

webSocket在.net中的使用案例

前言前面asp.net实现长连接 - chenxizhaolu - 博客园学习了如何在asp.net中实现http长连接,这里继续学习websocket。WebSockets 是一种协议,它能让客户端和服务器之间通过单个长期连接进行无缝通信。与 HTTP 等遵循请求-响应模式的传统网络通信方法不同,WebSockets 引入了全…

SQL SERVER日常运维巡检系列之-性能

前言做好日常巡检是数据库管理和维护的重要步骤,而且需要对每次巡检日期、结果进行登记,同时可能需要出一份巡检报告。本系列旨在解决一些常见的困扰:不知道巡检哪些东西 不知道怎么样便捷体检 机器太多体检麻烦 生成报告困难,无法直观呈现结果 性能是系统好坏的重要指标之…

burpsuite激活

激活burpsuite——教程点击Start 文件,把三个框都选上点击RUN,会自动启动,复制一下那个证书粘贴刚刚复制的密钥,点击下一个即可这里点击手动激活,复制请求,粘贴到刚刚那个激活程序的:Activation Request 它会自动生成Response,Copy就行到Burpsutie 里面复制一下,然后点…

KBP310-ASEMI整流桥稳定电力的核心担当

KBP310-ASEMI整流桥稳定电力的核心担当编辑:ll 在当今电子科技飞速发展的时代,各类电子设备充斥着我们的生活,从日常使用的手机、电脑,到工业生产中的大型机械,稳定的电力供应都是它们正常运转的基石。而在这背后,有一个常常被忽视却又至关重要的元件 ——KBP310 整流桥。…

GraphQL开发工具选型指南:Apipost高效调试与文档生成实战解析

GraphQL 调试与文档生成:Apipost 如何简化开发流程 GraphQL开发工具选型指南:Apipost高效调试与文档生成实战解析 GraphQL 凭借其灵活的数据查询能力和高效的接口设计,是现代 API 开发的主流选择。根据 State of JS 2022 的调研,GraphQL 在开发者中的采用率已超过 40%,尤其…

大数据在项目管理中的应用:5个预测分析模型+工具

随着信息技术的飞速发展,大数据在各个领域的应用日益广泛,项目管理也不例外。大数据的分析和应用为项目管理带来了新的机遇和挑战,通过预测分析模型和工具,项目管理者可以更好地规划、执行和监控项目,提高项目的成功率和效益。本文将介绍大数据在项目管理中的应用,重点探…