首页 > 解决方案 > 使用 BeautifulSoup 从 html 中提取除 script 标签内容外的文本

问题描述

我有这样的html

<span class="age">
    Ages 15
    <span class="loc" id="loc_loads1">
     </span>
     <script>
        getCurrentLocationVal("loc_loads1",29.45218856,59.38139268,1);
     </script>
</span>

我正在尝试Age 15使用BeautifulSoup

所以我写了python代码如下

代码:

from bs4 import BeautifulSoup as bs
import urllib3

URL = 'html file'

http = urllib3.PoolManager()

page = http.request('GET', URL)

soup = bs(page.data, 'html.parser')
age = soup.find("span", {"class": "age"})

print(age.text)

输出:

Age 15 getCurrentLocationVal("loc_loads1",29.45218856,59.38139268,1);

我只想要标签Age 15内的功能。script有没有办法只得到文本:Age 15?或任何方式来排除script标签的内容?

PS:脚本标签太多,URL不同。我不喜欢替换输出中的文本。

标签: pythonpython-3.xbeautifulsoupurllib3

解决方案


利用.find(text=True)

前任:

from bs4 import BeautifulSoup

html = """<span class="age">
    Ages 15
    <span class="loc" id="loc_loads1">
     </span>
     <script>
        getCurrentLocationVal("loc_loads1",29.45218856,59.38139268,1);
     </script>
</span>"""

soup = BeautifulSoup(html, "html.parser")
print(soup.find("span", {"class": "age"}).find(text=True).strip())

输出:

Ages 15

推荐阅读