Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

How to click iframe button on Python using Selenium?

I am trying to automate changing Facebook passwords using Python. I would like to be able to press the "Save Changes" button in the security settings after entering the password, but I'm not sure how I can do that.

    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'")

Thanks to some help, the first part works. It's able to log into Facebook, navigate to the security settings, and type in the passwords. I tried figuring out how the XPath works and this was my attempt at the end. Any advice is appreciated!

question from:https://stackoverflow.com/questions/65713769/how-to-click-iframe-button-on-python-using-selenium

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You dont have to switch again as you are already inside the iframe: Just use below 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'")

use relative xpath :

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

As the fields are html form you can directly use submit method also instead of clicking the save changes:

  password_confirm.submit()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...