python - 无法使用 python 中的 selenium webdriver 发送 key

标签 python selenium selenium-webdriver webdriver

我是 Python 新手,我只是想编写一段代码来在浏览器中打开新选项卡。所以我搜索了一些方法来做到这一点,并且遇到了这个过程。但是尽管它在 YouTube 视频中运行得很好我的根本不起作用。它只打开一个新窗口并转到 google.com。但它不会按 ctr+t 打开新选项卡。我不知道为什么,因为它甚至没有在 python shell 中显示任何错误。希望有人能帮助我解决这个问题并告诉我我的代码有什么问题。谢谢

#! python3

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
browser=webdriver.Firefox()
browser.get('http://www.google.com')
elm=browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL+'t')
time.sleep(2)
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL+Keys.PAGE_DOWN)

最佳答案

这是一个code snipped在 selenium 中打开一个新选项卡:

import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys
from time import sleep    

browser = webdriver.Firefox()
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 mistaken with tab... not the same)
main_window = browser.current_window_handle

# Open the link in a new tab by sending key strokes on the element
# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack 
first_link.send_keys(Keys.CONTROL + Keys.RETURN)

# Switch tab to the new tab, which we will assume is the next one on the right
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

# Put focus on current window which will, in fact, put focus on the current visible tab
browser.switch_to_window(main_window)

# do whatever you have to do on this page, we will just got to sleep for now
sleep(2)

# Close current tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

# Put focus on current window which will be the window opener
browser.switch_to_window(main_window)

关于python - 无法使用 python 中的 selenium webdriver 发送 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53712586/

相关文章:

python - 合并两个 Pandas 数据框多对一

python - 带 pandas 的表枢轴

python - 使用 Python 中的 matplotlib 从线性模型绘制 3d 曲面图

java - 在 Mac OS 上使用 Gecko 驱动程序执行 selenium 测试时显示 'failed to lookup address information' 错误

java - 启动 ChromeDriver 时出现异常

python - 下载完成后如何关闭浏览器?

javascript - 如何点击包含变量为 "href"属性的链接?

java - 无法找到存在的元素,获取 NullPointerException 而不是 NoSuchElement

java - org.openqa.selenium.WebDriverException 错误的根本原因是什么?

python - 内置函数与递归函数