我有这样的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/