使用 selenium 打開一個新選項卡后,我嘗試在新選項卡中查找一個元素 - 但腳本仍在從前一個選項卡中搜索 html 腳本。如何使它在我打開一個新選項卡后搜索打開的選項卡的 HTML 而不是以前的?
下面是我的代碼(它不起作用,因為我嘗試在新選項卡上搜索元素,但腳本在第一個選項卡上搜索它)。
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Users\\jack_l\\AppData\\Local\\Google\\Chrome\\User Data")
options.add_argument(r'--profile-directory=Profile 8')
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
#Opens the Chrome browser
driver.get("https://www.beatstars.com/")
#Opens a new tab on the browser and goes to that URL
driver.execute_script("window.open('https://www.tunestotube.com/', 'new window')")
#Doesn't work since it's searching for a "tunestotube" element on "beatstars"
theText = driver.find_element(By.XPATH, "/html/body/div[2]/div[2]/div[2]").text
任何幫助將不勝感激。
uj5u.com熱心網友回復:
driver.execute_script("window.open('https://www.tunestotube.com/', 'new window')")
driver.switch_to.window( driver.window_handles[1])
theText = driver.find_element(By.XPATH, "/html/body/div[2]/div[2]/div[2]").text
當您打開選項卡時,您會獲得一個句柄,您需要切換回前一個句柄,然后找到您的元素。
uj5u.com熱心網友回復:
找到解決辦法:需要切換到新視窗
下面是在第一個選項卡上獲取網站的代碼,用另一個網站打開一個新選項卡,然后可以讀取/查找該新選項卡中的元素。
#Gets a browser and sets the window to a variable
driver.get("https://www.exampleWebsiteForFirstTab.com/")
window_before = driver.window_handles[0]
#Open a new tab and sets the window to a variable
driver.execute_script("window.open('https://www.exampleWebsiteForSecondTab.com/', 'new window')")
window_after = driver.window_handles[1]
#Switches the current window to the new tab
driver.switch_to.window(window_after)
###DO WHATEVER YOU WANT IN THE NEW TAB
#Switches the current window to the old tab
driver.switch_to.window(window_before)
希望這可以幫助任何遇到我遇到同樣問題的人!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/471176.html
下一篇:Python&Selenium:如何避免來自divide.com的StaleElementReferenceException錯誤
