Mvd*_*vdD 2 python wsgi werkzeug flask python-requests
我一直在使用 Flasktest_client对象来测试我的 Web 应用程序。我使用BeautifulSoup来解析其中一些调用的 HTML 输出。
现在我想尝试使用requests-html,但我不知道如何让它与 Flask 测试客户端一起工作。示例都使用请求包来获取响应,但 Werkzeug 测试客户端并没有进行实际的 HTTP 调用。据我所知,它设置了环境并只调用处理程序方法。
有没有办法使这项工作无需运行实际服务?
requests-wsgi-adapter提供了一个适配器来挂载在 URL 上可调用的 WSGI。您用于session.mount()安装适配器,因此对于requests-html,您将HTMLSession改为使用并安装到该适配器。
$ pip install flask requests-wsgi-adapter requests-html
Run Code Online (Sandbox Code Playgroud)
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<p>Hello, World!</p>"
Run Code Online (Sandbox Code Playgroud)
from requests_html import HTMLSession
from wsgiadapter import WSGIAdapter
s = HTMLSession()
s.mount("http://test", WSGIAdapter(app))
Run Code Online (Sandbox Code Playgroud)
r = s.get("http://test/")
assert r.html.find("p")[0].text == "Hello, World!"
Run Code Online (Sandbox Code Playgroud)
使用请求的缺点是您必须"http://test/"在要向其发出请求的每个 URL 之前添加。Flask 测试客户端不需要这个。
除了使用 requests 和 requests-html,您还可以告诉 Flask 测试客户端返回一个为您进行 BeautifulSoup 解析的响应。快速浏览 requests-html 后,我仍然更喜欢直接 Flask 测试客户端和 BeautifulSoup API。
$ pip install flask beautifulsoup4 lxml
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
r = c.get("/")
assert r.html.p.text == "Hello, World!"
Run Code Online (Sandbox Code Playgroud)
您还应该考虑使用HTTPX而不是请求。它是一个现代的、维护良好的 HTTP 客户端库,与请求共享许多 API 相似之处。它还具有异步、HTTP/2 和直接调用 WSGI 应用程序的内置功能等强大功能。
$ pip install flask httpx
Run Code Online (Sandbox Code Playgroud)
c = httpx.Client(app=app, base_url="http://test")
Run Code Online (Sandbox Code Playgroud)
with c:
r = c.get("/")
html = BeautifulSoup(r.text)
assert html.p.text == "Hello, World!"
Run Code Online (Sandbox Code Playgroud)