简体   繁体   中英

How to click a button inside a frame using python, selenium?

I am trying to click on the "Edit" button in the Facebook "Change password" security settings through Python.

 # logs in to facebook
    browser = webdriver.Chrome(executable_path='/path/to/webdriver')

    # Navigate to Facebook
    browser.get("http://www.facebook.com")

    browser.maximize_window()

    # Search & Enter the Email or Phone field & Enter Password
    username = browser.find_element_by_id("email")
    username.send_keys("email@gmail.com")
    password = browser.find_element_by_id('pass')
    password.send_keys('password')
    submit = browser.find_element_by_name('login')
    submit.click()
    print("logged in")
    time.sleep(5)

    # navigates to security
    browser.get("http://www.facebook.com/settings?tab=security")
    time.sleep(3)

I'm completely new at this, but this code so far runs, and logs into the facebook page, and goes to the security settings. I can't figure out how to click the button, however. Using Inspect, I wasn't able to find an ID and after a lot of googling, I think it may be an issue concerning Frames? Any advice would be helpful!

The element is within an <iframe> so you have to:

  • Induce WebDriverWait for the desired frame to be available and switch to it .

  • Induce WebDriverWait for the desired element to be clickable .

  • You can use either of the following Locator Strategies :

    • Using XPATH :

       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()
  • Note : You have to add the following imports:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a couple of relevant discussions in:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM