Skip to main content
 首页 » 编程设计

python之在新选项卡中打开链接并在选项卡之间切换(Selenium WebDriver + Python)

2025年05月04日28sxdcgaq8080

<分区>

我有这样的注释代码:

import selenium.webdriver as webdriver 
import selenium.webdriver.support.ui as ui 
from selenium.webdriver.common.keys import Keys 
 
 
browser = webdriver.Chrome() 
browser.get("https://www.google.com?q=python#q=python") 
first_result = ui.WebDriverWait(browser, 15).until(lambda browser:  
browser.find_element_by_class_name("rc")) 
first_link = first_result.find_element_by_tag_name("a") 
 
# Save the window opener (current window, do not mistake with tab...  
not the same). 
main_window = browser.current_window_handle 
 
# Open the link in a new tab by sending keystrokes on the element. 
first_link.send_keys(Keys.COMMAND + "t") 
 
# Switch tab to the new tab, which we will assume is the next one on  
the right and put focus. 
browser.find_element_by_tag_name("body").send_keys(Keys.COMMAND +  
Keys.NUMPAD2) 
 
# Close current tab. 
browser.find_element_by_tag_name("body").send_keys(Keys.COMMAND + "w") 
 
# Put the focus on the current window which will be the window opener. 
browser.switch_to.window(main_window) 

但它不起作用(脚本挂起)——first_link 未在新选项卡中打开。 关于它还有其他想法吗?谢谢。

PS:我在 macOS 上。