使用 bs4 搜索 <span> 时得到空结果

Getting empty result when searching for <span> with bs4

我想在我的 Flask-App 中使用 bs4 来搜索特定范围。

我以前从未使用过 bs4,所以我有点困惑为什么我的搜索没有得到任何结果。

from bs4 import BeautifulSoup

url = "https://www.mcfit.com/de/fitnessstudios/studiosuche/studiodetails/studio/berlin-lichtenberg/"
html_content = requests.get(url).text
soup = BeautifulSoup(html_content, "lxml")

spans = soup.find_all('span', {'class': 'sc-fzoXWK hnKkAN'})
print(spans)

class 'sc-fzoXWK hnKkAN' 只包含 1 个跨度。 当我执行时,我只得到一个 [] 作为结果。

这些内容是使用 javascript 动态生成的,因此使用请求检索 HTML 只会检索静态内容,您可以将 BeautifulSoup 与类似 Selenium 的东西结合起来实现您的目标想要:

安装硒:

pip install selenium

然后使用 Firefox 引擎或任何其他支持 javascript 的引擎检索内容:

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('https://www.mcfit.com/de/fitnessstudios/studiosuche/studiodetails/studio/berlin-lichtenberg/')


html_content = driver.page_source
soup = BeautifulSoup(html_content, "lxml")

elems = soup.find_all('div', {'class': 'sc-fzoXWK hnKkAN'})
print(elems)

如果您使用 Firefox,geckodriver 需要可以通过您的脚本访问,您可以从 https://github.com/mozilla/geckodriver/releases 下载它并将其放入您的 PATH(或者 c:/windows 如果您正在使用这个 OS) 所以它随处可见。