Opening tabs using selenium based on user input

吃可爱长大的小学妹 提交于 2021-02-11 12:20:45

问题


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

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