2016-05-07 149 views
7

我想使用Selenium WebDriver & Python在不同的選項卡中打開相當多的URL。Selenium將不會在新選項卡(Python和Chrome)中打開新的URL

我不知道是怎麼回事錯誤:

driver = webdriver.Chrome() 
driver.get(url1) 
time.sleep(5) 
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL+'t') 
url2 = 'https://www.google.com' 
driver.get(item2) 

我擡頭一看教程,並在我看來,就好像此代碼應該做我想做的。實際上發生的事情是瀏覽器打開,url1打開,因爲它應該打開一個新的選項卡,因爲它應該然後url2加載在原來的選項卡而不是新的(即使新標籤似乎是活動的)。我試圖找到一個解決方案,但無濟於事。我試圖找到一個解決方案,但無濟於事。我使用Chrome瀏覽器,因爲當使用Firefox時,我不能得到它加載任何URL。 )

有什麼我可以改變我的代碼來獲得新的URL在新標籤中打開?

感謝您的幫助!

回答

7

有一個在ChromeDriver防止CTRL /命令+ T從工作中的錯誤:

你可以做什麼,作爲一種解決方法,是在新打開一個鏈接然後切換到新窗口使用switch_to.window()。工作樣本:

from selenium import webdriver 
from selenium.webdriver import ActionChains 
from selenium.webdriver.common.keys import Keys 

driver = webdriver.Chrome() 
driver.get("https://www.google.com") 

# open a link in a new window 
actions = ActionChains(driver) 
about = driver.find_element_by_link_text('About') 
actions.key_down(Keys.CONTROL).click(about).key_up(Keys.CONTROL).perform() 

driver.switch_to.window(driver.window_handles[-1]) 
driver.get("https://stackoverflow.com") 

現在最後driver.get()將在新打開的選項卡中進行。

+0

謝謝,但該錯誤似乎是關於CTRL-T沒有打開一個新的選項卡。我可以打開一個新標籤,但不會在該標籤中加載一個網址。我試過你的代碼,但我可能不明白它的正確。 find_element_by_link行發生錯誤(無法定位元素)。我正在加載一個html頁面(頁面源代碼),我不確定這是否有所作爲。 – SamH123

+0

@ SamH123好的,在你的情況下,你只需要在打開一個新選項卡後執行'driver.switch_to.window(driver.window_handles [-1])'。 – alecxe

+0

非常感謝,這工作! – SamH123

8

這裏有一個簡單的方法,獨立於平臺:

代碼:

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

切換回原來的標籤:

代碼:

driver.switch_to_window(driver.window_handles[0]) 

檢查當前標題請確保您位於右側頁面:

代碼:

driver.title 

對於一切,玩得開心!

+0

我使用的是Chrome Webdriver,它實際上在一個新標籤中打開,非常感謝 – PossessWithin

5

另一種打開新窗口的方法是使用JavaScript和窗口處理程序在它們之間切換。

driver = webdriver.Chrome() 

# Open a new window 
# This does not change focus to the new window for the driver. 
driver.execute_script("window.open('');") 

# Switch to the new window 
driver.switch_to.window(driver.window_handles[1]) 
driver.get("http://stackoverflow.com") 

# close the active tab 
driver.close() 

# Switch back to the first tab 
driver.switch_to.window(driver.window_handles[0]) 
driver.get("http://google.se") 

# Close the only tab, will also close the browser. 
driver.close() 

如果你看看你的瀏覽器,當你執行它看起來像新的窗口具有焦點,但對webdriver的,事實並非如此。不要被視覺所迷惑。還記得選擇一個新的窗口處理,當你關閉一個標籤,因爲它會設置driver.current_window_handle

selenium.common.exceptions.NoSuchWindowException: 
    Message: no such window: target window already closed from unknown error: web view not found 
    (Session info: chrome=<Your version of chrome>) 
    (Driver info: chromedriver=<Your chrome driver version> (<string of numbers>),platform=<Your OS>) 
.close()

,如果你試圖做的東西與在該階段,驅動程序將拋出這個錯誤。

相關問題