python—我正在尝试创建这个注解机器人,它在其中添加注解,而注解本身不会重复

4dc9hkyq  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(363)

# this is the section where I think I need help

def random_comment():
    with open('comments.txt', 'r') as f:
        comments = [line.strip() for line in f]
    comment = random.choice(comments)
    return comment        

    #comment=============================

    for url in urls:
        print('Commenting to this post ---> ' + url)
        comment = random_comment()
        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('Skipped - comments disabled')
        else:
            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(comment)

注解位于.txt文件名comments.txt中。出于此测试目的,注解为1,2,…,10,每行上都有一个数字。我想让评论机器人在不重复数字的情况下对它们进行评论。如果可能,甚至在注解后删除该编号。

9njqaruj

9njqaruj1#

如果您想在不重复的情况下做出选择,您可以执行以下操作:
只需读取comments.txt一次,并将所有注解的列表保存在变量中。
做出选择后,您需要从所有评论列表中删除该选择。
例如:

class Comments:
   def __init__(self):
     with open('comments.txt', 'r') as f:
       self.comments = [line.strip() for line in f]

   def choice_comment(self):
     comment = random.choice(self.comments)
     self.comments.remove(comment)
     return comment

如果要从注解中删除编号(如果文件看起来像:

1. One comment
2. Two comment
........
10. Ten comment

),您可以按点拆分字符串,并将所有字符串连接回,而不使用第一个字符串(它是一个数字):

comment = '. '.join(comment.split('. ')[1:])

相关问题