鍍金池/ 問答/Python/ 使用Flask調(diào)用selenium后的輪詢問題

使用Flask調(diào)用selenium后的輪詢問題

本人正在寫一個selenium爬蟲的網(wǎng)頁面板,用flask控制selenium的一些行為。目標(biāo)網(wǎng)頁需要掃描二維碼登陸,現(xiàn)在卡在掃描二維碼完成登陸后這個階段,因?yàn)橄氩坏饺绾卧趺磳?shí)現(xiàn)登錄后進(jìn)行狀態(tài)輪詢,并返回到Flask進(jìn)而觸發(fā)網(wǎng)頁元素變化。具體代碼如下:

from flask import Flask,render_template,request,redirect,url_for
from Control import control
from flask import session,escape
from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'dqwer235r*tbqew4r1$1232~@'
test = control()
socketio = SocketIO(app)

@app.route('/',methods=['GET','POST'])
def login():
    try:
        if request.method == 'POST':
            uname = request.form['username']
            passwd = request.form['password']
            if uname == 'admin' and passwd == '123456':
                session['username'] = 'admin'
                return redirect(url_for('dashboard'))

    except Exception as e:
        return render_template('homepage.html',error=e)

    return render_template('homepage.html')

@app.route('/dashboard/',methods=['GET','POST'])
def dashboard():
    if request.method == 'GET'and request.headers.get("Referer") == 'http://127.0.0.1/':
            if 'username' in session:
                if session['username'] == 'admin':
                    if 'QRstatus' in session and session['QRstatus'] == 'True':
                        if test.ck_login():
                            return render_template('dashboard.html',msg='Logined.',qrSrc=test.ck_login())
                        else:
                            session['QRstatus'] = 'False'
                    else:
                        # TODO: Add not login status
                        return render_template('dashboard.html')
            else:
                return redirect(url_for('login'))

    elif request.method == 'POST':
        if request.form['submit'] == 'Start':
            if 'QRstatus' in session and session['QRstatus'] == 'True':
                return render_template('dashboard.html',msg='QR code was printed.',qrSrc=test.ck_login())
            msg = 'Started.'
            qrSrc = test.qr()
            session['QRstatus'] = 'True'
            return render_template('dashboard.html',msg=msg,qrSrc=str(qrSrc))
        else:
            msg = 'no'
            return render_template('dashboard.html',msg=msg)
    return render_template('dashboard.html')

if __name__ == '__main__':
    socketio.run(app,port=80)

   

selenium的部分:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException,StaleElementReferenceException

class img_url_match(object):
    def __init__(self,locator,text_):
        self.locator = locator
        self.text = text_

    def __call__(self, driver):
        try:
            img_src = EC._find_element(driver,self.locator).get_attribute('src')
            return img_src.startswith(self.text)
        except StaleElementReferenceException:
            return False


class control:
    def __init__(self):
        self.driver = webdriver.Chrome()

    def qr(self):
        self.driver.get('http://example.com')
        try:
            while True :
                if not WebDriverWait(self.driver,2).until(img_url_match((By.ID,'js_login_qrcode_img'),'data:image/gif;base64')):
                    continue
                else:
                    qr_src = self.driver.find_element_by_id('js_login_qrcode_img').get_attribute('src')
                    return qr_src
        except TimeoutException:
            self.driver.refresh()

    def ck_login(self):
        if self.driver.current_url == 'http://example.com':
            try:
                url = WebDriverWait(self.driver,25).until(EC.url_changes('http://example.com'))
                return 'data:image/gif;base64,' +self.driver.get_screenshot_as_base64()
            except TimeoutException:
                return False
        elif self.driver.current_url == 'http://example.com/home/':
            return 'data:image/gif;base64,' + self.driver.get_screenshot_as_base64()
        elif self.driver.current_url == ':data:,':
            print('Now the url is :' + self.driver.current_url)
            WebDriverWait(self.driver,5).until(EC.presence_of_element_located((By.ID,'js-ch-member-face')))
            return 'data:image/gif;base64,' + self.driver.get_screenshot_as_base64()

if __name__ == '__main__':
    test = control()
    print(test.qr())

現(xiàn)在我打算用協(xié)程或者subprocess來進(jìn)行selenium某些狀態(tài)的輪詢,但不知這樣會不會啟動另一個新的selenium實(shí)例,即開啟一個新的瀏覽器?另外使用tornado會不會好些?

謝謝大家。

回答
編輯回答
溫衫

現(xiàn)在的解決方案是網(wǎng)頁端setInterval結(jié)合socketio進(jìn)行狀態(tài)判斷

2017年8月14日 22:47