大家好,我刚开始学习使用selenium
写一个操作浏览器的小脚本。
我想在一个火狐浏览器窗口下新开n个标签页,我在网上查到可以使用键盘事件:Keys.CONTROL + 't'
实现,确实能够生效。
但问题是,接下来我需要操作这些新打开的标签页,网上的方法是通过driver.window_handles
获取句柄。按道理说六个tab
应该获取6个句柄,但是我输出发现始终只有一个句柄,我的代码如下:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox() # 默认的火狐浏览器
for i in range(5):
# 这句代码相当于在浏览器窗口下按下ctrl+t打开一个新的标签页
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
handles = driver.window_handles
print(len(handles))
print(handles)
输出:
1
['{1deb296c-6cdc-4838-b143-1ee67ae0effd}']
只有一个句柄,因此我无法操作全部的tabs
谁能指点我一下其中的原因?或者提供一种可以新建n个标签页并且能够不断切换和操作它们的方法,谢谢大家!
I also used selenium recently and encountered this problem when opening a new window. I couldn't get all the handles using window_handles.
I thought about it for two days and found a lot of information. . . When I ran my script again, I found that my new window had not been fully opened (not accurate, because I don’t know how to describe this), so I could add a sleep time, or use other methods to determine the new window. Whether the window has been fully opened is more accurate than sleep