Reputation: 141
I'm loggin on Instagram with Python3 + Selenium, I'm using Google Chrome. When I login I always get 2 popup windows, I have tried to locate them with their xpath in order to close them.
Unfortunately Selenium doesn't find them, and I always get this error message:
Traceback (most recent call last):
File "mycode.py", line 61, in <module>
driver.find_element_by_xpath('/html/body/div[4]/div/div/div/div[3]/button[2]').click()
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[4]/div/div/div/div[3]/button[2]"}
My Code:
# Load page
driver.get("https://www.instagram.com/accounts/login/")
# Login
driver.find_element_by_xpath("//div/input[@name='username']").send_keys(username)
driver.find_element_by_xpath("//div/input[@name='password']").send_keys(psw)
driver.find_element_by_xpath("//span/button").click()
print('1st popup window\n')
driver.find_element_by_xpath('/html/body/div[4]/div/div/div/div[3]/button[2]').click()
print('2nd popup window\n')
driver.find_element_by_xpath("/html/body/div[2]/div/button").click()
I retrieved the xpath directly from the browser, so it shouldn't be the cause of this problem. Does anybody know how to resolve this? Thanks!
Upvotes: 1
Views: 2731
Reputation: 131
One way to solve this problem is to use explicit waits. An explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code. Maybe the button takes time to become visible and before it is visible, Selenium looks for it and cannot find it, therefore throwing an error. To take care of this issue, try the following:
button = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "yourXPATH")))
button.click()
The above code will wait up to 10 seconds until the button element is found; if it is not found in 10 seconds, Selenium will throw a TimeoutException error.
The following imports are necessary for the code to work:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
More on explicit waits can be found in this website- http://selenium-python.readthedocs.io/waits.html
Upvotes: 1