Selenium python-如果在调用driver.close()之前我的脚本失败,然后再次调用该函数,我是否将打开两个驱动程序?

时间:2019-03-06 15:12:41

标签: python selenium

作为第二个问题,如果我同时运行两个单独的Selenium脚本,它们是否会相互干扰,或者它们会创建单独的实例?

我实际上是在使用这些信息登录我的银行。我担心如果我进入登录过程的中途(三个单独的页面),然后第二个脚本试图从头开始启动它,则可能会导致混乱。

根据问题,我已经包含了我的功能:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from bs4 import BeautifulSoup
import time
import json
import traceback

def scrapeBank(bank, return_dict):

    try:

        remote = 1
        debug = 0

        if remote == 1:
            from pyvirtualdisplay import Display
            display = Display(visible=0, size=(800, 600))
            display.start()
            options = webdriver.ChromeOptions()
            options.add_argument('--no-sandbox')
            options.add_argument('--disable-extensions')
            options.add_argument('--headless')
            options.add_argument('--disable-gpu')
            driver = webdriver.Chrome(chrome_options=options)
        else:
            driver = webdriver.Chrome()

        [do a bunch of stuff]

        print('Bank Scrape completed')  
        driver.close()
        return_dict['transactions'] = transactions


    except:
        print(traceback.format_exc())
        driver.close()

1 个答案:

答案 0 :(得分:0)

  

只要创建一个新的实例/对象,就可以在其中运行它   相同的脚本(您无需再次运行该脚本)

如果您多次启动脚本,则每次运行python都会创建一个新对象,因此您无法控制其他驱动程序

这里是创建1个对象的方法:

driver = webdriver.Chrome('/path/to/chromedriver')  

多个看起来像这样:

driver1 = webdriver.Chrome('/path/to/chromedriver')  
driver2 = webdriver.Chrome('/path/to/chromedriver')  
driver3 = webdriver.Chrome('/path/to/chromedriver')  
driver4 = webdriver.Chrome('/path/to/chromedriver')  

然后您可以像这样使用它们:

driver1.get('http://www.google.com')
driver2.get('http://www.youtube.com')
driver3.get('http://www.facebook.com')
driver4.get('http://www.stackoverflow.com')

对于您的代码,您没有关于关键字及其正确用法的基本知识。 try表示它将执行代码,如果有错误,它将执行except中的操作。然后,您有一个无用的条件:if remote == 1:始终是正确的,上面的cuz 2行是:remote = 1 ...无论如何,您的问题是不同的...您在询问是否使用此功能函数,如果浏览器彼此干扰...答案是NO,如上所述,每次创建新实例/对象时,它都是全新的driver。原因在这里:driver = webdriver.Chrome(chrome_options=options)

try:
    remote = 1
    debug = 0
    if remote == 1:
        from pyvirtualdisplay import Display
        display = Display(visible=0, size=(800, 600))
        display.start()
        options = webdriver.ChromeOptions()
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-extensions')
        options.add_argument('--headless')
        options.add_argument('--disable-gpu')
        driver = webdriver.Chrome(chrome_options=options)
    else:
        driver = webdriver.Chrome()

    [do a bunch of stuff]

    print('Bank Scrape completed')  
    driver.close()
    return_dict['transactions'] = transactions
except:
    print(traceback.format_exc())
    driver.close()