use*_*410 7 python iframe selenium webdriver
我正在尝试搜索我使用selenium webdriver访问的所有网站的html.在selenium中,当我有一个iframe时,我必须切换到iframe,然后切换回主html来搜索其他iframe.
但是,对于嵌套的iframe,这可能非常复杂.我必须切换到iframe,搜索iframe,然后切换到找到一个iframe,搜索IT for iframes,然后转到另一个iframe我必须切换到主框架,然后保存我的路径以切换回我所在的位置之前等等
不幸的是,我发现很多网页在iframe中的iframe中都有iframe(依此类推).
有一个简单的算法吗?或者更好的方法呢?
我无法找到具有多层嵌套框架的网站来完全测试这个概念,但我能够在只有一层嵌套框架的网站上测试它.因此,这可能需要一些调试来处理更深层的嵌套.此外,此代码假定每个iframe都具有name属性.
我相信沿着这些方向使用递归函数将为您解决问题,这里是一个示例数据结构:
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
Run Code Online (Sandbox Code Playgroud)
你可以通过调用:来启动它frametree = iframe_search([]),framedict最终看起来像这样:
frametree =
{'child1' : 'framepath' : [], 'children' : {'child1.1' : 'framepath' : ['child1'], 'children' : {...etc}},
'child2' : 'framepath' : [], 'children' : {'child2.1' : 'framepath' : ['child2'], 'children' : {...etc}}}
Run Code Online (Sandbox Code Playgroud)
注意:我写这篇文章的原因是使用框架的属性来识别它们而不是仅仅使用find_elements方法的结果是我发现在某些情况下Selenium会在页面打开后抛出过时的数据异常太久了,这些反应不再有用了.显然,框架的属性不会改变,因此使用xpath会更稳定.希望这可以帮助.
仅通过 HTML 元素标记或属性(包括 ID)查找 iframe 似乎不可靠。
另一方面,通过 iframe 索引递归搜索的效果相对较好。
def find_all_iframes(driver):
iframes = driver.find_elements_by_xpath("//iframe")
for index, iframe in enumerate(iframes):
# Your sweet business logic applied to iframe goes here.
driver.switch_to.frame(index)
find_all_iframes(driver)
driver.switch_to.parent_frame()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6713 次 |
| 最近记录: |