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?

Ratmir Asanov
  • 6,237
  • 5
  • 26
  • 40
Luke Vanzweden
  • 466
  • 3
  • 15
  • 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: https://stackoverflow.com/a/37337963/2225619 – Capricorn Aug 08 '18 at 13:07

1 Answers1

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.

Shivam Mishra
  • 1,731
  • 2
  • 11
  • 29