无法使用Python和Selenium打开新的Firefox选项卡 [英] Can't open a new Firefox tab with Python and selenium

查看:223
本文介绍了无法使用Python和Selenium打开新的Firefox选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个FireFox配置文件,我想打开一个配置文件,打开几个具有不同URL的选项卡,打开另一个配置文件并打开带有URL的选项卡. 由于某种原因,send_keys似乎不起作用,但是window.open起作用. 到目前为止,这是我的代码.

I have multiple FireFox profiles and I want to open a profile, open a few tabs with diffrent URLs, open another profile open tabs with URLs. For some reason send_keys does not seem to work, but window.open does. This is my code, so far.

import os
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
p1 = webdriver.FirefoxProfile(profile_directory="C:/Users/User/AppData/Roaming/Mozilla/Firefox/Profiles/4yopmm8r.py")
driver = webdriver.Firefox(firefox_profile=p1)
driver.get("https://www.reddit.com/")
time.sleep(5)
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + "t")
driver.get("https://www.stackoverflow.com/")

它所做的只是打开reddit,等待5秒钟,然后打开stackoverflow. 我该如何解决?

All it does is open reddit, wait 5 seconds and then open stackoverflow. How do I fix this?

推荐答案

您可以使用execute_script打开选项卡.这是示例代码.

You can open the tab using the execute_script. Here is the sample code.

#navigate to reddit in base tab
driver.get("https://www.reddit.com/")
time.sleep(5) # actually you can wait for one of the element present status.
base_tab = driver.window_handles[0]

#open the new tab and navigate to SO
driver.execute_script("window.open('https://www.stackoverflow.com/')")
latest_tab = driver.window_handles[-1]

# use .swith_to.window to access the desired tab
driver.switch_to.window(base_tab)
driver.switch_to.window(latest_tab)

通过索引访问标签的其他方式使用driver.window_handles,这将为您提供窗口列表.现在,您可以按索引选择标签(以0开头)

Other way to access the tab by index Using driver.window_handles, which will give you the list of windows. Now you can choose the tabs by index (starts with 0)

# base tab
driver.switch_to.window(driver.window_handles[0])
# second tab
driver.switch_to.window(driver.window_handles[1])
# latest tab
driver.switch_to.window(driver.window_handles[-1])

重要的是在打开新选项卡之前,请确保第一个窗口已完全加载,否则window_handles与您期望的顺序不匹配.因为window_handles仅在选项卡完全加载后才考虑它.

It's important to make sure the first window is loaded completely before opening the new tab, otherwise the window_handles does not match the order you expect. Because window_handles will consider the tab only once it's completely loaded.

这篇关于无法使用Python和Selenium打开新的Firefox选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆