1 回答

TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
請(qǐng)求-wsgi 適配器提供了一個(gè)適配器,用于在 URL 上掛載可調(diào)用的 WSGI。您可以使用會(huì)話.mount()
來(lái)掛載適配器,因此對(duì)于請(qǐng)求-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!"
使用請(qǐng)求的缺點(diǎn)是,您必須在要向其發(fā)出請(qǐng)求的每個(gè)URL之前添加。Flask 測(cè)試客戶端不需要這樣做。"http://test/"
除了使用請(qǐng)求和請(qǐng)求-html 之外,您還可以告訴 Flask 測(cè)試客戶端返回一個(gè)響應(yīng),該響應(yīng)將為您執(zhí)行美麗蘇美解析。在快速瀏覽了請(qǐng)求-html之后,我仍然更喜歡直接的燒瓶測(cè)試客戶端和美麗湯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!"
您還應(yīng)該考慮使用 HTTPX 而不是請(qǐng)求。它是一個(gè)現(xiàn)代的,維護(hù)良好的HTTP客戶端庫(kù),與請(qǐng)求共享許多API相似之處。它還具有出色的功能,例如異步,HTTP / 2以及直接調(diào)用WSGI應(yīng)用程序的內(nèi)置功能。
$ 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!"
添加回答
舉報(bào)