python - 硒按钮单击不触发内联javascript事件处理程序
问题描述
我的 HTML 如下所示
<div class="container">
<div class="jumbotron">
<h1 id="survey-title" class="display-5 text-capitalize">Your favourite candidate</h1>
<hr class="my-4">
<div class="card-body">
<h5 id="question-title" class="card-title">What is your name?</h5>
<form id="question_form" action="/survey/takesurvey/1/2" method="post" class="form">
<input type="hidden" name="csrfmiddlewaretoken" value="ELBWYGZRxRuI7CoZ2xkmgCJ3f9JweFMM4Ew1pQbgSE3BLb38VStPJEbHvsyiBEFg">
<div class="form-group"><input type="text" name="response" value="asdfasdfas" maxlength="400" class="form-control" title="" id="id_response"></div>
</form>
</div>
<a id="btn-previous" href="javascript:history.back()" class="btn btn-primary ">Previous</a>
<a id="btn-next" href="/survey/takesurvey/finish/1" class="btn btn-primary">Next</a>
</div>
</div>
注意href
上一个按钮
<a id="btn-previous" href="javascript:history.back()" class="btn btn-primary ">Previous</a>
单击下一步将提交表单并转到“下一页”,再次单击“上一页”应返回并保留上一页中的输入值。我正在使用以下代码来测试此行为,以下代码仅在我sleep(1)
在查找元素和单击之间添加线时才有效。否则页面不会返回(网址不会改变)
- 为什么在单击按钮之前等待 url 更改不起作用
- 我怀疑它与未加载的javascript事件处理程序(在html中内联)有关。
- 我有什么方法可以检查页面是否准备好点击事件
cur_url = self.browser.current_url
self.browser.find_element_by_id('btn-next').click()
wait(lambda: self.assertNotEqual(self.browser.current_url, cur_url))
btn_previous = self.browser.find_element_by_id('btn-previous')
## This code is not working without the sleep below. Which I suspect
## has to do with javascript event handler (which is inline in html) not being loaded.
## Is there better way to check that the button is ready to be clicked
sleep(1)
btn_previous.click()
解决方案
您可以使用WebDriverWait
条件element_to_be_clickable
。也检查这里。
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(self.browser, 5).until(EC.element_to_be_clickable((By.ID, "btn-previous"))).click()
您可以尝试等待 JavaScript:
WebDriverWait(self.browser, 20).until(lambda d: d.execute_script(
'return (document.readyState == "complete" || document.readyState == "interactive")'))
# or without interactive
WebDriverWait(self.browser, 20).until(lambda d: d.execute_script(
'return document.readyState == "complete"'))