我有以下Selenium Test for Python / Django应用程序:
class EmailRecordsTest(StaticLiveServerTestCase):
def test_can_store_email_and_retrieve_it_later(self):
self.browser.get(self.live_server_url)
emailbox = self.browser.find_element_by_xpath("//form[@class='pma-subscribe-form']/input[1]")
self.assertEqual(emailbox.get_attribute("placeholder"), 'Enter your Email')
print("tested until here")
print("The placeholder: ", emailbox.get_attribute("placeholder"))
print(emailbox)
emailbox.send_keys('vio@mesmerizing.com')
从打印运行中可以清楚地看到首次出现的emailbox,并为占位符断言Equal。 emailbox.send_keys的最后一个实例抛出以下错误:
selenium.common.exceptions.ElementNotVisibleException: Message:
Element is not currently visible and so may not be interacted with
使用send_keys时无法找到相同元素变为不可见的原因。
正在测试的Html代码如下:
<!-- Start footer -->
<footer id="pma-footer">
<!-- start footer top -->
<div class="pma-footer-top">
<div class="container">
<div class="pma-footer-top-area">
<div class="row">
<div class="col-lg-3 col-md-3 col-sm-3">
<div class="pma-footer-widget">
<h4>News letter</h4>
<p>Get latest update, news & offers</p>
<form class="pma-subscribe-form">
<input id="subscribe-email" type="email" placeholder="Enter your Email">
<button class="btn btn-danger btn-md" type="submit">Subscribe!</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end footer top -->
请帮助。
答案 0 :(得分:1)
实际上find_element
会返回DOM
上可能存在的元素,无论它是否可见,您也可以获得此元素的属性,但send_keys
会对元素和selenium的操作只会对可见元素执行操作,因此您需要确保在对元素执行操作之前使用WebDriverWait
进行操作,如下所示: -
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
wait = WebDriverWait(driver, 10)
emailbox = wait.until(EC.visibility_of_element_located((By.ID, "subscribe-email")))
#do your all stuff before send keys
# now use send_keys
emailbox.send_keys('vio@mesmerizing.com')
已修改: - 如果您仍无法与元素互动,请尝试使用execute_script()
设置值,如下所示: -
emailbox = wait.until(EC.presence_of_element_located((By.ID, "subscribe-email")))
#do your all stuff before send keys
# now use execute_script
driver.execute_script("arguments[0].value = 'vio@mesmerizing.com'", emailbox)
答案 1 :(得分:0)
在这种情况下工作的另一个选项是滚动到特定元素(位于页面底部),然后使用它工作的send_keys。
emailbox = self.browser.find_element_by_xpath("//form[@class='mu-subscribe-form']/input[1]")
self.browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
emailbox.send_keys('vio@mesmerizing.com')