Selenium 单击 Instagram 上的所有关注按钮 Python

Selenium Clicking all follow buttons on instagram Python

我正在尝试在您点击 Instagram 网站上的用户用户名时自动点击 Instagram 关注按钮。

点击用户名后,您会点击关注者,然后会打开一个 window,其中包含关注此人的人,并且有关注按钮

这是新 window

的屏幕截图

我试图通过 python selenium 一个一个地点击按钮,但我尝试的似乎没有任何效果。

我得到的最好的是一个 for 循环,它只使用 xpath 单击了第一个跟随按钮,但没有单击其他按钮。

#click the followers button to dispaly the users followers
driver.find_element_by_partial_link_text("followers").click()
time.sleep(3)
#scroll through the followers list to a specified heeight
scroll_box=driver.find_element_by_xpath("/html/body/div[4]/div/div[2]")
last_ht, ht=0, 1
while last_ht !=ht:
    last_ht=ht
    time.sleep(2)
    ht=driver.execute_script("""arguments[0].scrollTo(0, 2000);
    return 2000;
    """, scroll_box)
#follow users up to the specified height
follow=driver.find_elements_by_xpath("/html/body/div[4]/div/div[2]/ul/div/li[1]/div/div[3]/button")
for x in range (0,len(follow)):
        follow[x].click()
        time.sleep(2)

    time.sleep(1)

您的 Xpath 选择器似乎是直接从 chrome 开发人员工具复制的,顺便说一句,它只会 return 一个按钮,因为您的目标是一个 li

# Get all buttons that has the text Follow 
buttons = driver.find_elements_by_xpath("//button[contains(.,'Follow')]")
for btn in buttons:
    # Use the Java script to click on follow because after the scroll down the buttons will be un clickeable unless you go to it's location
    driver.execute_script("arguments[0].click();", btn)
    time.sleep(2)

如果我们已经关注了某人并且它问我这个怎么办:

如果我想在这段代码中添加 if 语句:

#scroll through the followers list to a specified heeight
# Get all buttons that has the text Follow 
buttons = self.driver.find_elements_by_xpath("//button[contains(.,'Follow')]")

for btn in buttons:
    self.driver.execute_script("arguments[0].click();", btn)
    sleep(99)

后来现场开始给出这个消息it is blocking my action to click on followe

Yash,我无法对你的回答发表评论,所以我发布了另一个。

解决方法: 您需要在点击前检查按钮文字,

if btn.text == 'Follow':
    #Code to click button