python - 使用 BeautifulSoup 从 html 中仅提取除脚本标签内容之外的文本

标签 python python-3.x beautifulsoup urllib3

我有这样的html

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

我正在尝试使用 BeautifulSoup 提取 Age 15

于是我写了如下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: there are too many script tags and different URLS. I don't prefer replace text from the output.

最佳答案

使用.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

关于python - 使用 BeautifulSoup 从 html 中仅提取除脚本标签内容之外的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53701062/

相关文章:

python - sys.stdout.write\r回车,如何覆盖所有字符?

python - 如何使用 Python 访问受 IAP 保护的资源?

python - xlabel 和 ylabel 值未在 matplotlib 散点图中排序

python - 在 PyBrain 神经网络中创建自定义连接

c++ - ctypes wintypes WCHAR 字符串 附加空格

python - 如何在 Python 中正确解析 Git 命令 (`git log ...` )?

python - 如何在python中使 Mechanize 脚本多线程

python - BeautifulSoup 没有获取元标记

python - 如何在 Beautifulsoup 中分解 HTML 元素以将它们插入到 MySQL 数据库表中?

python - 如何制作 "python setup.py install"安装源而不是 egg 文件?