Search code examples
pythonpython-3.xsplinter

how to use flask driver in python splinter


all my code is just:

from splinter import Browser
from flask import Flask, request
from splinter.driver.flaskclient import FlaskClient
app = Flask(__name__)

browser = Browser('flask', app=app)
browser.visit('https://www.google.com')
print(browser.html)

which print the 404 html: 404 Not Found

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

there is anything I should do?


Solution

  • You are getting a 404 error because your Flask app has no routes.

    I believe the purpose of the Splinter Flask client is to test your Flask app, not to test/request other domains. Visiting another domain with the Splinter Flask client will simply request the URL from your domain. You have not specified any routes for your Flask app, so Flask is responding with a 404 error.

    Here's an example that shows how the Splinter Flask client is working:

    # define simple flask app
    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return 'Hello, World!'
    
    @app.route('/<name>')
    def hello_world(name):
        return 'Hello, {name}!'.format(name=name)
    
    # initiate splinter flask client
    from splinter import Browser
    browser = Browser('flask', app=app)
    
    # simple flask app assertions
    browser.visit('http://127.0.0.1:5000')
    assert browser.html == 'Hello, World!'
    browser.visit('http://127.0.0.1:5000/haofly')
    assert browser.html == 'Hello, haofly!'
    
    # Notice that requesting other domains act as if it's your domain
    # Here it is requesting the previously defined flask routes
    browser.visit('http://www.google.com')
    assert browser.html == 'Hello, World!'
    browser.visit('http://www.google.com/haofly')
    assert browser.html == 'Hello, haofly!'
    

    Here's another test that demonstrates what's really going on:

    from flask import Flask
    app = Flask(__name__)
    
    @app.errorhandler(404)
    def page_not_found(e):
        return 'Flask 404 error!', 404
    
    from splinter import Browser
    browser = Browser('flask', app=app)
    
    browser.visit('http://www.google.com/haofly')
    assert browser.html == 'Flask 404 error!'