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!"
使用请求的缺点是您必须在要向其发出请求的每个 URL 之前添加"http://test/"。 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 和 call WSGI applications directly 的内置功能。
$ 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!"