0

So I'm trying to open a new window by executing a script in Selenium using driver.execute_script("window.open('');")

But I want to open a link given by the user.

So I got the link input from my array and put it to my javascript code just like this:

driver.execute_script("window.open(data[0]);")

Now It's giving an error like this:

selenium.common.exceptions.JavascriptException: Message: javascript error: data is not defined

How to fix this? Thanks for your time.

EDIT: A part of my code is something like that:

from selenium import webdriver
import PySimpleGUI as sg
import time

global data

data = []

layouts = [[[sg.Text("Enter the Wordpress New Post link: "), sg.InputText(key=0)]],
          [sg.Button('Start The Process'), [sg.Button('Exit')]]]

window = sg.Window("Title", layouts)


def selenium_process():
    # Getting the driver path
    driver = webdriver.Chrome(r'Driver\path')
    driver.get('https://google.com')
    driver.execute_script(f"window.open({data[0]});")
    time.sleep(10000)


while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Exit'):
        break
    data.append(values[0])
    selenium_process()

1 Answers1

0

did you try string interpolation ?

Try this:

driver.execute_script(f"window.open({data[0]});")

Your solution does not work since data[0] is a string, not a variable. You instead need to substitute data[0] with its value (must be a value that JS can understand).

Please read the description of Javascript window.open : https://developer.mozilla.org/fr/docs/Web/API/Window/open

If you just need to get to an URL:

driver.get(data[0])
  • Now I'm facing with this error:`selenium.common.exceptions.JavascriptException: Message: javascript error: missing ) after argument list` – Wordpress4Love May 11 '21 at 11:48
  • @Wordpress4Love can you detail what data should contain ? – Jérome Eertmans May 11 '21 at 11:55
  • I added my code to thread. – Wordpress4Love May 11 '21 at 12:11
  • I have tested you code but I do not really understand what it is supposed to do ? Because if you just want to load a webpage, why not using webdriver.get(url) instead ? (I have uptaded my answer above) – Jérome Eertmans May 12 '21 at 15:01
  • I want to open multiple windows at the same time with a loop. For example, user will choose 6 posts to post on Wordpress and bot will open 6 windows and in every window, It'll go to new post page and write the article. – Wordpress4Love May 13 '21 at 13:50
  • Hello ! Sorry for the delay, did you try these : https://stackoverflow.com/questions/18150593/selenium-multiple-tabs-at-once, especially the answer from Marisco ? – Jérome Eertmans May 18 '21 at 08:05