问题
I'm trying to make a script where the program takes input of multiple URLs and then opens tabs for each of them, this is what I came up with
s=raw_input()
l=s.split()
t=len(l)
for elements in l:
elements = ["https://" + elements + "" for elements in l]
driver = webdriver.Chrome(r"C:/Users/mynam/Desktop/WB/chromedriver.exe")
driver.get("https://www.google.com")
for e in elements:
driver.implicitly_wait(3)
driver.execute_script("window.open(e,'new window')")
print "Opened in new tab"
I get an error of e not defined, how do we pass an argument to window.open in selenium
回答1:
You need to execute new window, switch to it and open new page.
from selenium import webdriver
import os
def open_tab_page(page, page_number):
browser.execute_script("window.open('');")
browser.switch_to.window(browser.window_handles[page_number])
browser.get(page)
# initialise driver
chrome_driver = os.path.abspath(os.path.dirname(__file__)) + '/chromedriver'
browser = webdriver.Chrome(chrome_driver)
browser.get("http://stackoverflow.com/")
# list of pages to open
pages_list = ['https://www.google.com', 'https://www.youtube.com/']
page_number = 1
for page in pages_list:
open_tab_page(page, page_number)
page_number +=1
来源:https://stackoverflow.com/questions/59999987/opening-tabs-using-selenium-based-on-user-input