我正在制作一个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,
我建议您跟随所有人之后,可以将文件中的所有名称读取到列表/集中,然后将不在列表/集中的名称添加到其中。然后只需覆盖旧文件即可。
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))