我正在使用python selenium创建一个web服务,当它被调用时会对页面执行一些指令,但问题是使用flask蓝图将'driver'类传递给另一个页面。
main.py
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options as chrome_options
from classes.send_message import send_message
from flask import Flask
from flask_restful import Resource, Api
from flask import request
app = Flask(__name__)
api = Api(app)
app.register_blueprint(send_message)
if __name__ == '__main__':
logging.info('START APP')
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\myuserpath........")
driver = webdriver.Chrome(executable_path="chromedriver.exe", chrome_options=options)
driver.get("https://example.com")
app.run(host='192.168.50.1', port='11111',debug=False)
send_message.py
from flask import Blueprint
#from flask import current_app as app
send_message = Blueprint('send_message', __name__)
@send_message.route("/SendPostMessage")
def sendMessage():
side_panel = driver.find_element_by_id('menutop') # error here!!!
错误:
File "C:\python36\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\rararara\classes\send_message.py", line 8, in sendMessage
side_panel = driver.find_element_by_id('menutop')
NameError: name 'driver' is not defined
答案 0 :(得分:2)
您可以将app对象用作上下文:
...
driver.get("https://example.com")
app.driver = driver
app.run(host='192.168.50.1', port='11111',debug=False)
然后
from flask import current_app as app
...
@send_message.route("/SendPostMessage")
def sendMessage():
side_panel = app.driver.find_element_by_id('menutop')