gpanterov
gpanterov

Reputation: 1395

Unable to locate a visible element with python selenium

I would like to click on a calendar entry in this site using selenium in python. Although I can clearly see each calendar entry and I can get its xpath, id etc. But when I try to locate the element I get an errror. (For example, I can see that the link for the 20th day of April has an id='20160420')

browser = webdriver.Firefox(firefox_profile=fp)
browser.get(url)
browser.implicitly_wait(5)
el=browser.find_element_by_id('20160420')

Any suggestions (I tried switching between frames, active elements etc. but to no avail so far ...)

Upvotes: 1

Views: 1409

Answers (2)

WeezyKrush
WeezyKrush

Reputation: 494

The issue seems to be that the element that you are looking for is in an iframe, and you have to switch to that before you can access the calendar element:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as WDW
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException,     TimeoutException, StaleElementReferenceException


url = 'https://hornblowernewyork.com/cruises/international-sightseeing-cruise'
browser = webdriver.Firefox()
browser.get(url)

# seach for the appropriate iframe
frame = browser.find_element(By.CSS_SELECTOR, "#crowdTorchTicketingMainContainer > iframe")
if not frame:
  raise Exception('Frame not found')

# once the correct iframe is found switch to it, 
# then look for your calendar element
browser.switch_to.frame(frame)
try:
  el = WDW(browser, 10).until(
    EC.presence_of_element_located((By.ID, "20160406"))
  )
except (TimeoutException, NoSuchElementException, StaleElementReferenceException), e:
  print e
else:
  print el

Upvotes: 0

Buaban
Buaban

Reputation: 5137

The problem is your code didn't switch to iframe yet. See example code below:

browser = webdriver.Firefox(firefox_profile=fp)
browser.get(url)
browser.implicitly_wait(5)
time.sleep(5)
iframe = browser.find_element_by_css_selector('#crowdTorchTicketingMainContainer > iframe')
browser.switch_to.frame(iframe)
el=browser.find_element_by_id('20160420')
print(el.text)

Upvotes: 2

Related Questions