首页 > 解决方案 > 在不启动服务器的情况下使用 requests-html 测试 Flask 应用程序

问题描述

我一直在使用 Flasktest_client对象来测试我的 Web 应用程序。我使用BeautifulSoup来解析其中一些调用的 HTML 输出。

现在我想尝试requests-html,但我不知道如何使它与 Flask 测试客户端一起工作。这些示例都使用请求包来获取响应,但是 Werkzeug 测试客户端并没有进行实际的 HTTP 调用。据我所知,它设置环境并调用处理程序方法。

有没有办法让这项工作而不必运行实际的服务?

标签: pythonflaskpython-requestswsgiwerkzeug

解决方案


requests-wsgi-adapter提供了一个适配器来在 URL 上挂载一个 WSGI 可调用对象。您用于session.mount()挂载适配器,因此对于requests-html您将HTMLSession改为使用并挂载到该适配器。

$ pip install flask requests-wsgi-adapter requests-html
from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "<p>Hello, World!</p>"
from requests_html import HTMLSession
from wsgiadapter import WSGIAdapter

s = HTMLSession()
s.mount("http://test", WSGIAdapter(app))
r = s.get("http://test/")
assert r.html.find("p")[0].text == "Hello, World!"

使用请求的缺点是您必须"http://test/"在要向其发出请求的每个 URL 之前添加。Flask 测试客户端不需要这个。


除了使用 requests 和 requests-html,您还可以告诉 Flask 测试客户端返回一个为您进行 BeautifulSoup 解析的响应。快速浏览 requests-html 后,我还是更喜欢直接的 Flask 测试客户端和 BeautifulSoup API。

$ pip install flask beautifulsoup4 lxml
from flask.wrappers import Response
from werkzeug.utils import cached_property

class HTMLResponse(Response):
    @cached_property
    def html(self):
        return BeautifulSoup(self.get_data(), "lxml")

app.response_class = HTMLResponse
c = app.test_client()
r = c.get("/")
assert r.html.p.text == "Hello, World!"

您还应该考虑使用HTTPX而不是请求。它是一个现代的、维护良好的 HTTP 客户端库,与请求有许多 API 相似之处。它还具有异步、HTTP/2 和直接调用 WSGI 应用程序的内置功能等强大功能。

$ pip install flask httpx
c = httpx.Client(app=app, base_url="http://test")
with c:
    r = c.get("/")
    html = BeautifulSoup(r.text)
    assert html.p.text == "Hello, World!"

推荐阅读