【发布时间】:2019-10-27 03:50:18
【问题描述】:
我正在尝试使用 Selenium Python 自动执行网页导航。我想单击一个执行 JavaScript 代码的 HTML 按钮,该代码验证按钮是否专注于 onclick 操作。
在这种特定情况下,我使用 Selenium 选择有效对象没有问题,但是简单的 element.click() 似乎不起作用。
HTML 源代码:
<td width="1%">
<!--Begin /jsp/com/tibco/wfc/ButtonUI.jsp-->
<script language="javascript">
var isFocus = "false";
</script>
<button class="button_normal" name="OK" style="width:100px" onfocus="isFocus='true'" onblur="isFocus='false'" onmouseover="this.className='button_rollover'" onmouseout="this.className='button_normal'" onmousedown="this.className='button_pressed'" onmouseup="this.className='button_rollover'"
onclick="javascript:if(isFocus=='false'){ return false}; showProgressMeter();submitCommand(event,'com_tibco_wfc_Button_498466961', 'com_tibco_wfc_DefaultFrame_1501194824', false, false, 'null', 'o', '', false);;return false;">OK</button>
<!--End /jsp/com/tibco/wfc/ButtonUI.jsp-->
</td>
Python/Selenium 属性:
warning_ok_button = driver.find_element_by_xpath("//button[@name='OK']")
attrib = driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;',warning_ok_button)
pprint(attrib)
{'class': 'button_normal',
'name': 'OK',
'onblur': "isFocus='false'",
'onclick': "javascript:if(isFocus=='false'){ return false}; "
"showProgressMeter();submitCommand(event,'com_tibco_wfc_Button_498466961', "
"'com_tibco_wfc_DefaultFrame_1501194824', false, false, 'null', "
"'o', '', false);;return false;",
'onfocus': "isFocus='true'",
'onmousedown': "this.className='button_pressed'",
'onmouseout': "this.className='button_normal'",
'onmouseover': "this.className='button_rollover'",
'onmouseup': "this.className='button_rollover'",
'style': 'width:100px'}
warning_ok_button.click() 似乎只是将按钮的类从button_normal 更改为button_rollover
【问题讨论】:
-
什么浏览器?我在 C# 中使用过 selenium,有时您必须运行 JavaScript 才能为您执行点击操作(尤其是在 IE 中)。其他时候你必须使用一个动作——例如:stackoverflow.com/a/13938778/9538369
-
在本例中是 Firefox。我尝试了以下方法,但仍然失败(按钮类从 button_normal 更改为 button_rollover):
python actions = ActionChains(driver) actions.move_to_element(warning_ok_button).click() actions.perform() -
您是否尝试过执行脚本来单击按钮。我知道这并不理想,但有时它是必要的。我还注意到,如果您在某些操作之间睡觉,则操作可以正常工作 - 这也可能是您的问题。
-
检查
driver.execute_script("arguments[0].click()",warning_ok_button)是否触发了javascript。 -
@supputuri:这个建议很好,但这次恐怕行不通了。
标签: javascript python selenium