无法在python中使用Selenium Webdriver发送密钥

时间:2018-12-10 19:46:38

标签: 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)

1 个答案:

答案 0 :(得分:1)

这里是code snipped,用于在硒中打开一个新标签页:

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)