Send keys control + click in Selenium with Python bindings

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

I need to open link in new tab using Selenium.

So is it possible to perform ctrl+click on element in Selenium to open it in new tab?

回答1:

Use an ActionChain with key_down to press the control key, and key_up to release it:

import time from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys  driver = webdriver.Chrome()  driver.get('http://google.com') element = driver.find_element_by_link_text('About')  ActionChains(driver) \     .key_down(Keys.CONTROL) \     .click(element) \     .key_up(Keys.CONTROL) \     .perform()  time.sleep(10) # Pause to allow you to inspect the browser.  driver.quit() 


回答2:

Two possible solutions:

opening a new tab

self.driver = webdriver.Firefox() self.driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')  

this is the solution for MAC OSX. In other cases you can use the standard Keys.CONTROL + 't'

opening a new webdriver

driver = webdriver.Firefox() #1st window second_driver = webdriver.Firefox() #2nd windows  


回答3:

Below is what i have tried for Selenium WebDriver with Java binding and its working for me. If you want to manually open the Link in New Tab you can achieve this by performing Context Click on the Link and selecting 'Open in new Tab' option. Below is the implementation in Selenium web-driver with Java binding.

Actions newTab= new Actions(driver); WebElement link = driver.findElement(By.xpath("//xpath of the element"));  //Open the link in new window newTab.contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform(); 

Web-driver handles new tab in the same way to that of new window. You will have to switch to new open tab by its window name.

driver.switchTo().window(windowName); 

You can keep track of window-names which will help you to easily navigate between tabs.



回答4:

Following is working for me to open link in new tab :

   String link = Keys.chord(Keys.CONTROL,Keys.ENTER);     driver.findElement(By.linkText("yourlinktext")).sendKeys(link); 

Above code is in java. you can convert to python easily I assume.

Please ask if have any query.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!