怎么在python selenium获取某个window打开的child window?

只有一个新页面的时候很好判断

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.a.com')
handles = browser.window_handles
parent_a = browser.current_window_handle
browser.execute_script('window.open("http://www.a1.com");')
new_handles = browser.window_handles
child_a = new_handles[-1]

当有多个页面新打开的时候,怎么判断哪个页面是从parent_a打开的?
这里不知道child_a的url/name都是随机的,并不确定,不能通过判断新打开页面的url/name来确定。

阅读 4.8k
1 个回答

我觉得可以在本地维护一个字典hierarchy_dict,类似于树形结构:

from selenium import webdriver
# maintain a local dict
# in python 3.6 the keys by default in order
# otherwise you could use OrderedDict for clarity
hierarchy_dict = {}

options = webdriver.ChromeOptions()
options.add_argument('--user-data-dir=C:/Users/xxx/AppData/Local/Google/Chrome/User Data/Default')
browser = webdriver.Chrome(chrome_options=options)

# 1
browser.get('https://www.baidu.com')
handles = browser.window_handles
parent_a = browser.current_window_handle
hierarchy_dict[parent_a] = []

# 2
browser.execute_script('window.open("https://segmentfault.com/q/1010000011120876");')
child_a = browser.window_handles[-1]

# append to father's list
# create a new list for child_a
hierarchy_dict[parent_a].append(child_a)
hierarchy_dict[child_a] = []

# 3 again open with parent
browser.switch_to.window(parent_a)
browser.execute_script('window.open("https://segmentfault.com/q/1010000011120876");')
child_b = browser.window_handles[-1]
hierarchy_dict[parent_a].append(child_b)
hierarchy_dict[child_b] = []

# 4 open with child_a
browser.switch_to.window(child_a)
browser.execute_script('window.open("https://segmentfault.com/q/1010000011120876");')
child_c = browser.window_handles[-1]
hierarchy_dict[child_a].append(child_c)
hierarchy_dict[child_c] = []

# so on and so force
print(hierarchy_dict)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题