我有像这样的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代码
code:
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)
output:
Age 15 getCurrentLocationVal("loc_loads1",29.45218856,59.38139268,1);
我只想 Age 15
不是 script
标签内的功能 . 有没有办法只获得文字: Age 15
?或以任何方式排除 script
标签的内容?
PS:脚本标签太多,URL不同 . 我不喜欢从输出中替换文本 .
2 回答
迟到的答案,但为了将来参考,你也可以使用decompose()删除
html
中的所有script
元素,即:使用
.find(text=True)
EX:
Output: