python - selenium新建了5个标签页但是通过window_handles只能获取一个句柄是怎么回事?
PHPz
PHPz 2017-04-17 17:43:59
0
1
570

大家好,我刚开始学习使用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个标签页并且能够不断切换和操作它们的方法,谢谢大家!

PHPz
PHPz

学习是最好的投资!

reply all(1)
洪涛

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

**import time**
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')
time.sleep(10)#等待所有窗口完全打开,10秒够用了, 不好用就判断新窗口是否完全打开  
handles = driver.window_handles
print(len(handles))
print(handles)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!