【问题标题】:Appending the correct values from a list从列表中附加正确的值
【发布时间】:2020-04-20 22:54:04
【问题描述】:

我正在制作一个 Instagram 机器人,并将该机器人关注的用户的姓名存储在 file.txt 中。

    unique_photos = len(pic_hrefs)  # TODO Let this run once and check whether this block of code works or not
    followers_list = []  # Contains the names of the people you followed

    for pic_href in pic_hrefs:
        driver.get(pic_href)
        sleep(2)
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        try:
            # Like this picture
            driver.find_element_by_xpath("//*[@aria-label='Like']").click()
            print("Picture liked")  # TODO After checking delete this line

            follow_button = driver.find_element_by_class_name('bY2yH')

            # Follow the user if not followed already
            if follow_button.text == "•\n" + "Follow":
                follow_button.click()
                followed = driver.find_element_by_class_name('e1e1d')
                followers_list.append(followed.text)
                with open("file.txt", 'a') as file:
                    file.write(",".join(followers_list))
                    file.write(",")

            else:
                continue

            for second in reversed(range(0, 3)):
                print_same_line("#" + tag + ': unique photos left: ' + str(unique_photos)
                                + " | Sleeping " + str(second))
                sleep(1)
        except Exception:
            sleep(2)
        unique_photos -= 1

这是file.txt中的最终结果:

kr.dramas_,kr.dramas_,marcelly.lds,kr.dramas_,marcelly.lds,espn

很明显,问题在于,当我附加整个 Followers_list(其中包含机器人关注的人的所有用户名)时,名称会重复。所以我需要一种只附加新名称的方法。 而且我知道我可以每次将代码更改为“w”以创建一个全新的文件,但这会产生问题,因为在我停止机器人之后,如果我不取消关注该列表中的用户并再次启动机器人我将丢失文件中的所有名称,这是我不想要的。

所以我需要一些建议,以便在机器人停止后 file.txt 看起来像这样:

kr.dramas_,marcelly.lds,espn,

【问题讨论】:

  • 在追加之前,您可以先读取文件,将其输出存储到列表中,将其与关注者列表进行比较,然后追加唯一项目而不是关注者列表 - 这有意义吗?
  • 好吧,这行得通。但我必须创建一个新功能和一切。所以我不认为这个解决方案是最佳的,但它可以完成工作。谢谢。

标签: python selenium instagram


【解决方案1】:

我建议,一旦您关注了所有人,您可以将文件中的所有名称读取到列表/集中,然后将不在列表/集中的名称添加到其中。然后简单地覆盖旧文件。

followers_list = [] # will be populated with follower names

with open("file.txt", 'r') as file:
  file_names = file.readline().split(",")

for follower in followers_list:
  if follower not in file_names:
    file_names.append(follower)

with open("file.txt", 'w') as file:
  file.write(",".join(file_names))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2021-08-08
    • 2016-07-14
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多