如何修改Python评论bot代码实现comments.txt评论不重复且用完可删除
自动评论bot去重及已发送评论自动删除解决方案
核心思路是预先全量读取所有待发送评论到内存列表,随机选取时直接从列表中移除该评论,只有确认发送成功后才将剩余评论回写到本地文件,从根源避免重复发送,同时实现已用评论自动删除。
代码修改说明
1. 新增评论读写工具函数
import random import time from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 读取本地所有待发送评论 def load_comments(): with open('comments.txt', 'r', encoding='utf-8') as f: return [line.strip() for line in f if line.strip()] # 发送成功后更新本地评论文件,移除已发送评论 def save_remaining_comments(comments): with open('comments.txt', 'w', encoding='utf-8') as f: f.write('\n'.join(comments))
2. 修改主业务逻辑
# 程序启动时一次性加载所有评论 comments = load_comments() for url in urls: # 待发送评论为空时直接终止运行 if not comments: print('所有评论已发送完毕,程序终止') break print('正在对帖子发送评论:' + url) # 随机选取一条评论并从内存列表移除,天然避免重复选取 selected_comment = comments.pop(random.randint(0, len(comments)-1)) bot.get(url) bot.implicitly_wait(1) time.sleep(5) bot.find_element_by_xpath('//*[@id="react-root"]/section/main/div/div/article/div[3]/section[1]/span[2]/button').click() if doesnt_exist(bot, '//*[@id="react-root"]/section/main/section/div'): print('跳过:当前帖子评论区已关闭') # 评论区不可用时将选中的评论放回列表,避免浪费 comments.append(selected_comment) else: try: find_textarea = ( By.XPATH, '//*[@id="react-root"]/section/main/section/div/form/textarea') WebDriverWait(bot, 50).until( EC.presence_of_element_located(find_textarea) ) comment_box = bot.find_element(*find_textarea) WebDriverWait(bot, 50).until( EC.element_to_be_clickable(find_textarea) ) comment_box.click() comment_box.send_keys(selected_comment) # -------------------------- # 此处补充你原代码缺失的点击发送按钮逻辑 # -------------------------- # 发送无异常则更新本地评论文件,永久删除已发送评论 save_remaining_comments(comments) print(f'评论「{selected_comment}」发送成功,已从待发列表移除') except Exception as e: print(f'评论发送失败:{str(e)}') # 发送失败时将评论放回列表,后续可重试 comments.append(selected_comment)
注意事项
- 单实例运行该程序无任何冲突,若需多实例同时运行需额外加文件锁避免写入异常
- 确认发送逻辑执行成功后再调用
save_remaining_comments,避免误删未成功发送的评论 - 读写文件时指定
utf-8编码,兼容中文等非英文评论内容
内容的提问来源于stack exchange,提问作者Landry N.
相关产品推荐
相关产品推荐

