首页 > 解决方案 > Selenium 单击instagram Python上的所有关注按钮

问题描述

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

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

这是新窗口的屏幕截图

图片

我试图通过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)

标签: pythonseleniumautomationinstagram

解决方案


您的 Xpath 选择器似乎是直接从 chrome 开发人员工具复制而来的,顺便说一句,它只会返回一个按钮,因为您的目标是一个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)

推荐阅读