我正在尝试搜索所有使用selenium webdriver到达的网站的html。在硒中,当我有一个iframe时,我必须切换到该iframe,然后再切换回主html来搜索其他iframe。
但是,对于嵌套的iframe,这可能会非常复杂。我必须切换到一个iframe,在其中搜索iframe,然后切换到找到的一个iframe,在IT中搜索iframe,然后再转到另一个iframe,必须切换到主机,然后保存路径以切换回原来的位置之前等
不幸的是,我发现许多页面在iframe中的iframe中都有iframe(依此类推)。
为此有一个简单的算法吗?还是更好的方法呢?
我无法找到一个具有多层嵌套框架的网站来完全测试此概念,但是我只能在只有一层嵌套框架的站点上对其进行测试。因此,这可能需要一些调试才能处理更深层的嵌套。另外,此代码假定每个iframe都具有名称属性。
我相信,按照以下方式使用递归函数可以为您解决问题,下面是一个与之配套的示例数据结构:
def frame_search(path):
framedict = {}
for child_frame in browser.find_elements_by_tag_name('frame'):
child_frame_name = child_frame.get_attribute('name')
framedict[child_frame_name] = {'framepath' : path, 'children' : {}}
xpath = '//frame[@name="{}"]'.format(child_frame_name)
browser.switch_to.frame(browser.find_element_by_xpath(xpath))
framedict[child_frame_name]['children'] = frame_search(framedict[child_frame_name]['framepath']+[child_frame_name])
...
do something involving this child_frame
...
browser.switch_to.default_content()
if len(framedict[child_frame_name]['framepath'])>0:
for parent in framedict[child_frame_name]['framepath']:
parent_xpath = '//frame[@name="{}"]'.format(parent)
browser.switch_to.frame(browser.find_element_by_xpath(parent_xpath))
return framedict
您可以通过调用以下命令将其启动:frametree = iframe_search([])
,framedict
最终结果将如下所示:
frametree =
{'child1' : 'framepath' : [], 'children' : {'child1.1' : 'framepath' : ['child1'], 'children' : {...etc}},
'child2' : 'framepath' : [], 'children' : {'child2.1' : 'framepath' : ['child2'], 'children' : {...etc}}}
注意:我编写此文件以使用框架的属性来识别它们而不是仅使用find_elements方法的结果的原因是,我发现在某些情况下Selenium将在打开页面后引发陈旧的数据异常。时间过长,这些响应就不再有用。显然,框架的属性不会改变,因此使用xpath会更稳定。希望这可以帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句