问题:使用webdriver的find_element(by.XXX)无法找到页面隐藏对像并执行相应的操作
分析:页面使用display:none和visible:hidden将对应元素隐藏
display:none和visible:hidden的区别: -- 百度
* display:none ---不为被隐藏的对象保留其物理空间,即该对象在页面上彻底消失,通俗来说就是看不见也摸不到。
* visible:hidden--- 对象在网页上不可见,但对象在网页上所占的空间没有改变,通俗来说就是看不见但摸得到。
方法:selenium的webdriver提供了更底层的方法与网页元素对像进行交互,从而完成更为复杂的操作。实现: 参考 selenium.webdriver.common.action_chains
补充: 实现过程中发现其方法的执行速度非常慢,目前未找到原因。为了保证执行,采用了最暴力的手段,在执行的步骤中增加了等待时间Sleep().
经过观察,有可能是由于移动至目标对像时,弹出的子对像显示的时间不够长,无法捕获隐藏的子对像,继续实践中。
--2016/09/07, 考虑到长时间等待并不是解决问题的最终方法,因此通过点击后页面跳转后的特征值进行判断是否操作成功,如果成功则继续执行,否则执行对隐藏元素的操作,基本思路如下
<span style="font-family:Arial;font-size:10px;">def doElement(topelement, subelement):
do......
if isElementExist(element):
flag = True
try:
webdriver.find_element_by_XX(element)
return flag
except:
flag = false
return flag</span>
注: selenium.webdriver.common.action_chains
<span style="font-family:Microsoft YaHei;font-size:12px;">class ActionChains(__builtin__.object)
ActionChains are a way to automate low level interactions such as
mouse movements, mouse button actions, key press, and context menu interactions.
This is useful for doing more complex actions like hover over and drag and drop.
Generate user actions.
When you call methods for actions on the ActionChains object,
the actions are stored in a queue in the ActionChains object.
When you call perform(), the events are fired in the order they
are queued up.
ActionChains can be used in a chain pattern::
menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()
Or actions can be queued up one by one, then performed.::
menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
actions = ActionChains(driver)
actions.move_to_element(menu)
actions.click(hidden_submenu)
actions.perform()
Either way, the actions are performed in the order they are called, one after
another.
</span>