2

I have a text document with a single URL on every line. I want each URL to be opened in a new tab. Heres what I have so far:

tabs = 0
f = open('links.txt', 'r', encoding='utf-8')
for line in f:
    url = line
    driver.execute_script("window.open(url, 'new_window')")
    sleep(7) # time to let tge page load
    tabs = tabs + 1 # to keep track of how many tabs I have

This gives me the error:

Traceback (most recent call last): File "scraper.py", line 100, in driver.execute_script("window.open(url, 'new_window')") File "C:\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 635, in execute_script 'args': converted_args})['value'] File "C:\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: url is not defined

I have tried everything, but can't get it to work. Any Ideas?

1
  • As the error message statues, the js code you're executing has an undefined variable url. You need to pass the url as second parameter to the execute_script function, as it's currently only defined in your python context. Check this answer: stackoverflow.com/a/37337963/2225619 Commented Aug 8, 2018 at 13:07

1 Answer 1

2

You are trying to pass url variable incorrectly in execute_script. Do this instead -

    tabs = 0
    f = open('links.txt', 'r', encoding='utf-8')
    for line in f:
        url = line
        driver.execute_script("window.open(arguments[0])", url)
        sleep(7) # time to let tge page load
        tabs = tabs + 1 # to keep track of how many tabs I have

Where, arguments[0] refers to your url.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.