简体   繁体   English

烧瓶中硒的多个实例

[英]Multiple instance of Selenium in flask

I have these two endpoint:我有这两个端点:

@app.route('/api/v1/order', methods=['POST'])
def order():

        msg, return_data = bz.insertOrder()
        return msg, return_data


@app.route('/api/v1/offer', methods=['POST'])
def offer():
    msg, return_data = bz.insertOffer()
    return msg, return_data

Both functions call this, I strip some code lines:这两个函数都调用了这个,我去掉了一些代码行:

def insertOrder():
    return scrape(1)


def insertOffer():
    return scrape(2)

And finally scrape function is this, again it is just a snipped:最后刮功能是这样的,它只是一个片段:

def scrape(var):
    try:
        driver = webdriver.Safari()
        driver.get(login_url)
        elem = driver.find_element(By.NAME, "UserName")
        elem.clear()
        elem.send_keys(username)
        elemPwd = driver.find_element(By.NAME, "Password")
        elemPwd.clear()
        elemPwd.send_keys(password)
        elemPwd.send_keys(Keys.RETURN)
        time.sleep(1)
        ....
        driver.get(logout_url)
        driver.close()
        return '', http.HTTPStatus.CREATED
    except:
       driver.get(logout_url)
       driver.close()
       return 'Internal server error', http.HTTPStatus.BAD_REQUEST

I thounght to see multiple chrome browser open and close but as soon as I launch two post at the same time I got:我想看到多个 chrome 浏览器打开和关闭,但是当我同时发布两个帖子时,我得到了:

UnboundLocalError: local variable 'driver' referenced before assignment UnboundLocalError:分配前引用的局部变量“驱动程序”

You may run multiple instances of chrome browser if you do call two different instances of it in your code.如果您在代码中调用了两个不同的 chrome 浏览器实例,则可以运行多个 chrome 浏览器实例。 Your problem is you have only 1 driver declared but trying to involke the same driver您的问题是您只声明了 1 个驱动程序,但试图调用同一个驱动程序

from selenium import webdriver

def scrape(var):
     drivers =  
 [webdriver.Chrome(executable_path=r'C:\PATH\TO\DRIVER\chromedriver.exe'),  
 webdriver.Chrome(executable_path=r'C:\PATH\TO\DRIVER\chromedriver.exe')]

     [Your Logic here]

     drivers[var].get("YourURL")
    
     [more Logic here]

you may run more instances by declaring more webdrivers inside your drivers array.您可以通过在驱动程序数组中声明更多 webdrivers 来运行更多实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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