无法单击Iframe中的元素 - NoSuchElementException

时间:2018-01-17 14:15:35

标签: python selenium

我导航到网站,切换到正确的iframe,一切似乎都运行正常,但一旦我需要与元素进行交互,就会抛出错误:

selenium.common.exceptions.ElementNotVisibleException

CODE:

# IMPORT
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep

# NAVIGATE
driver = webdriver.Chrome("C:\\Program Files (X86)\\Google\\chromedriver.exe")
driver.get('http://www.foxnews.com/politics/2018/01/17/ice-plans-major-sweep-in-san-francisco-area-report-says.html')

# SWITCH TO IFRAME
iframe = driver.find_element_by_xpath('//IFRAME[contains(@src, "https://spoxy-shard4.spot.im/v2/spot/")]')
driver.switch_to.frame(iframe)

driver.find_element_by_xpath("//INPUT[@placeholder='Your nickname...']").click()

我也尝试过定位其他元素,但它总是会出错:

"no such element"
"element not found"
"is not clickable at point (485, 873). Other element would receive the click: <p class="alert-text">...</p>".

1 个答案:

答案 0 :(得分:1)

我访问了一个网站,我发现了两个问题,我不是100%肯定你正在尝试做什么,所以我在考虑你试图点击评论输入字段。

第一个问题 有时这个黄色横幅出现在底部,它位于所有元素的顶部,所以如果你试图点击下面的任何元素,你将获得ElementNotVisible异常,并留下其他元素可能收到的消息点击。

解决方案:等到横幅出现并且确实关闭横幅

第二个问题 您正试图点击隐藏的input field,因此即使没有展示横幅,您也会获得ElementNotVisible例外。

解决方案:不要点击input元素,而是点击它的父div

这是正在运行的代码。

 def is_element_exist(identifier, timeout=30):
    wait = WebDriverWait(driver, timeout)
    try:
        return wait.until(EC.presence_of_element_located(identifier))
    except TimeoutException:
        return None


def accept_alert(timeout=30):
    alert = WebDriverWait(driver, timeout).until(EC.alert_is_present())
    print alert.text
    driver.switch_to.alert.accept()


# NAVIGATE
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome("h:\\bin\\chromedriver.exe", )
driver.get('http://www.foxnews.com/politics/2018/01/17/ice-plans-major-sweep-in-san-francisco-area-report-says.html')

#Wait for yellow popup footer and close it
close_button = is_element_exist((By.XPATH, "//a[@class='close']"), 10)
if close_button:
    close_button.click()

# SWITCH TO IFRAME
iframe = driver.find_element_by_xpath('//IFRAME[contains(@src, "https://spoxy-shard4.spot.im/v2/spot/")]')
driver.switch_to.frame(iframe)

driver.find_element_by_xpath("//*[@class='sppre_editor']/div").click()

#Wait and accept the alert
accept_alert()