2017-09-26 258 views
0

我有這樣的代碼註釋:打開鏈接

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 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. 
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 focus on current window which will be the window opener. 
browser.switch_to.window(main_window) 

但它不工作(腳本掛) - first_link是不開放的新標籤。 還有其他想法嗎?謝謝。 PS:我在macOS上。

回答

1

您可以使用此代碼:

driver.execute_script("window.open('http://google.com', 'new_window')") 

切換:

driver.switch_to_window(driver.window_handles[0]) 

轉寄此Answer

+0

謝謝你的幫助! –

0

下面的代碼是現在的工作:

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

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 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. 
ActionChains(browser) \ 
.key_down(Keys.COMMAND) \ 
.click(first_link) \ 
.key_up(Keys.COMMAND) \ 
.perform() 

browser.switch_to.window(browser.window_handles[1]) 

time.sleep(5) 

# Close current tab. 
browser.close() 

time.sleep(5) 

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

# Close the instance of the browser. 
browser.quit() 

感謝您的幫助!