gpt4 book ai didi

python - 使用 Selenium 在 Mac 上打开选项卡、关闭选项卡并退出 Firefox?

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:57 24 4
gpt4 key购买 nike

我一直在四处寻找答案,但我的代码无法正常工作。我想要发生的是我可以打开一个选项卡,打开一个新网页,然后关闭同一个选项卡。从那里开始,一旦我完成了我的工作,我希望它退出该程序。截至目前,它不会打开新选项卡、关闭新选项卡和退出应用程序。现在正在做的是打开 google,然后在同一个选项卡中加载 stackoverflow。

现在,我有...

driver = webdriver.Firefox()
driver.get("https://www.google.com")
time.sleep(5)
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
time.sleep(5)
driver.get("https://www.stackoverflow.com")
time.sleep(5)
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'w')
time.sleep(5)
driver.Dispose()

有人有什么想法吗?

谢谢

最佳答案

尝试以下代码以获得所需的结果:

driver = webdriver.Firefox()
driver.get("https://www.google.com")
# Get current window/tab ID
current_window = driver.current_window_handle
# Open StackOverflow in new window/tab
driver.execute_script("window.open('https://www.stackoverflow.com')")
# Get new window/tab ID
new_window = [window for window in driver.window_handles if window != current_window][0]
# Switch to new window/tab
driver.switch_to.window(new_window)
# Close new window/tab
driver.close()
# Switch to initial window/tab
driver.switch_to.window(current_window)
# Quit Webdriver
driver.quit()

关于python - 使用 Selenium 在 Mac 上打开选项卡、关闭选项卡并退出 Firefox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47853073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com