推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
zmrenwu
V2EX  ›  Python

python selenium 如何实现对新建选项卡( tab)的操作?

  •  
  •   zmrenwu · Apr 2, 2016 · 11407 views
    This topic created in 3692 days ago, the information mentioned may be changed or developed.

    我现在有这样一个需求: 在一个浏览器窗口打开 n 个选项卡,然后让这 n 个选项卡打开同一个 url 并且不停地随机定位这 n 个选项卡中任意一个的某些元素,该如何实现?根据各种 google ,百度等的参考资料,我写了下面代码:

    url = r'xxxxxxx'
    driver = webdriver.Firefox()
    driver.get(url)
    

    此时创建了第一个浏览器窗口,然后我用下面的方法新建选项卡:

    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
    

    但是,这样新建的选项卡没有 handle ,没法 switch_to 这个选项卡,即使使用

    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + '\t')
    

    做强制切换,也没法通过 find 等方法定位这个选项卡里面的标签元素。

    有没有比较完美的解决方案?还是说 selenium 对选项卡操作不够支持?恳请大神指点。

    4 replies    2016-04-06 12:44:39 +08:00
    13k
        1
    13k  
       Apr 5, 2016
    driver.window_handles 返回 tab 列表
    然后 driver.switch_to_window 切换到对应的 tab
    zmrenwu
        2
    zmrenwu  
    OP
       Apr 6, 2016 via iPhone
    @13k 获取不到,由于只开了一个窗口,只能返回一个 handle
    13k
        3
    13k  
       Apr 6, 2016
    @zmrenwu 搞错, Chromedriver 可以, Firefox 没测
    zmrenwu
        4
    zmrenwu  
    OP
       Apr 6, 2016 via iPhone
    @13k 谢谢!我回去换用 chrome 测试一下!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3559 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 11:22 · PVG 19:22 · LAX 04:22 · JFK 07:22
    ♥ Do have faith in what you're doing.