【问题标题】:I'm trying to create this commenting bot, where it comments and the comments don't repeat them selves我正在尝试创建这个评论机器人,它在其中评论并且评论不会​​自我重复
【发布时间】:2021-09-19 08:21:10
【问题描述】:

#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)

       

cmets 在一个 .txt 文件名 cmets.txt 中 出于此测试目的,cmets 是 1,2,....,10,每个数字都在其行上。 我希望评论机器人在不重复数字的情况下评论它们。 如果可能的话,甚至在被评论后删除号码。

【问题讨论】:

    标签: python selenium selenium-webdriver bots


    【解决方案1】:

    如果你想在不重复的情况下做出选择,你可以做接下来的事情:

    1. 只读取一次 cmets.txt 并将所有 cmets 的列表保存在变量中。
    2. 做出选择后,您需要从所有 cmets 列表中删除该选择。

    例如:

    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:])
    

    【讨论】:

    • 它给了我这个错误:NameError: name 'self' is not defined
    • 如果你的代码中没有任何类,你的代码中不能使用self,你需要重写代码和使用函数所以,你需要把代码放在函数init中 在没有“self”的任何函数之外。 (你将变量“cmets”设为全局)。您还需要从choice_comment 函数中删除“self”。
    猜你喜欢
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 2022-11-18
    • 2013-07-10
    • 2021-10-02
    • 1970-01-01
    相关资源
    最近更新 更多