无法通过 Instagram 上的按钮定位/交互。硒

Can't locate / interact with button on Instargram via. selenium

我正在尝试使用 selenium 创建一个简单的 python 程序,需要找到并单击关注按钮。

这是HTML代码:

<div class="             qF0y9          Igw0E   rBNOH          YBx95   ybXk5    _4EzTm                      soMvl                                                                                        " id="f2d16737c928a4">

<button class="sqdOP  L3NKy   y3zKF     " type="button">Abonnieren</button>
</div>

我的python代码:

example = driver.find_element_by_xpath("//button[contains(@class,'sqdOP  L3NKy   y3zKF     ')]")
example.click

每次我尝试它都会给我:“selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法定位元素”

如果您想查看您需要登录的站点,然后转到建议页面,Instagram 会在其中建议您应该关注的人:https://www.instagram.com/explore/people/

您共享的 XPATH 似乎是一个 随机化的字符串,不会轻易迭代 其他后续按钮。我建议通过 HTML 页面获取“完整的 XPATH”,这样您就可以进行循环操作。请参阅下面的代码,了解点击关注按钮的循环:

count=1
while True:
      try:
            driver.find_element_by_xpath("/html/body/div[1]/div/div/section/main/div/div[2]/div/div/div["+str(count)+")]/div[3]/button").click()
            count=count+1
      except:
            break
driver.find_element_by_xpath("//button[.='Abonnieren']").click()

只需找到带有该文本的按钮并单击它。