简体   繁体   中英

Cant open multiple windows in selenium python in a function?

my question is why is it when i use driver.get in a for loop outside of a def function it works and opens multiple windows but when i use it inside a def function it only opens one and then refreshes that page. For example, say i tell it to open x amount windows i use this code,

def start():
  driver = webdriver.Chrome(chrome_path)
  ua = UserAgent()
  user_agent = ua.random
  for start_tasks in range(0, num_tasks):
  options.add_argument(f'user-agent={user_agent}')
  options.add_argument("window-size=600,600")
  options.add_argument('--disable-extensions')
  options.add_argument('--profile-directory=Default')
  options.add_argument("--disable-plugins-discovery")
  options.add_argument('--allow-running-insecure-content')
  options.add_argument("ignore-certificate-errors-spki-list")
  options.add_experimental_option("detach", True)
  driver.set_window_size(500, 500)
  driver.set_window_position(70, 70)
  driver.get(page_address)

(Sorry it copied weird) So anyways it takes a user input and then runs it that amount of times. For example i say to open 3 windows it should run 3 times, which it does outside of the def function. But inside it, it runs it once, and then reloads the page 2 more times. Does anyone have a clue of why this is happening?

Below code should work . You will need to create driver instance in loop

def start():
  driver = None
  ua = None
  for start_tasks in range(0, num_tasks):
      driver = webdriver.Chrome(chrome_path)
      ua = UserAgent()
      user_agent = ua.random
      options.add_argument(f'user-agent={user_agent}')
      options.add_argument("window-size=600,600")
      options.add_argument('--disable-extensions')
      options.add_argument('--profile-directory=Default')
      options.add_argument("--disable-plugins-discovery")
      options.add_argument('--allow-running-insecure-content')
      options.add_argument("ignore-certificate-errors-spki-list")
      options.add_experimental_option("detach", True)
      driver.set_window_size(500, 500)
      driver.set_window_position(70, 70)
      driver.get(page_address)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM