【问题标题】:How to click iframe button on Python using Selenium?如何使用 Selenium 在 Python 上单击 iframe 按钮?
【发布时间】:2021-01-14 05:15:57
【问题描述】:

我正在尝试使用 Python 自动更改 Facebook 密码。我希望能够在输入密码后按安全设置中的“保存更改”按钮,但我不知道该怎么做。

    browser.get("http://www.facebook.com/settings?tab=security")

    WebDriverWait(browser, 20).until(EC.frame_to_be_available_and_switch_to_it(
        (By.XPATH, "//iframe[starts-with(@src, 'https://www.facebook.com/settings?tab=security')]")))
    WebDriverWait(browser, 20).until(EC.element_to_be_clickable(
        (By.XPATH, "//td[.//span[text()='Change password']]//following-sibling::td[1]/button"))).click()
    print("clicked 'change password'")

    # fills in password info
    old_password = browser.find_element_by_id('password_old')
    old_password.send_keys("hello")
    new_password = browser.find_element_by_id('password_new')
    new_password.send_keys('hello123')
    password_confirm = browser.find_element_by_id('password_confirm')
    password_confirm.send_keys('hello123')
    print("password filled")

    # clicks Save Changes (doesn't work)
    WebDriverWait(browser, 20).until(EC.frame_to_be_available_and_switch_to_it(
        (By.XPATH, "//iframe[starts-with(@src, 'https://www.facebook.com/settings?tab=security')]")))
    WebDriverWait(browser, 20).until(EC.element_to_be_clickable(
        (By.XPATH, "//body/div[@id='mount_0_0']/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/iframe[1]"))).click()
    print("clicked 'change password'")

感谢一些帮助,第一部分有效。它能够登录 Facebook,导航到安全设置,然后输入密码。我试图弄清楚 XPath 是如何工作的,这是我最后的尝试。任何建议表示赞赏!

【问题讨论】:

    标签: python selenium authentication web-scraping


    【解决方案1】:

    您不必再次切换,因为您已经在 iframe 中:只需在 xpath 下方使用:

        WebDriverWait(browser, 20).until(EC.element_to_be_clickable(
            (By.XPATH, '(//input[@value="Save Changes" and @type="submit"])[1]'))).click()
        print("clicked 'change password'")
    

    使用相对 xpath :

    (//input[@value="Save Changes" and @type="submit"])[1]
    

    由于字段是html表单,您也可以直接使用提交方法,而不是点击保存更改:

      password_confirm.submit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-25
      • 2021-11-06
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 2021-01-31
      相关资源
      最近更新 更多