2 回答

TA貢獻1794條經驗 獲得超8個贊
用 .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

TA貢獻1982條經驗 獲得超2個贊
遲到的答案,但為了將來參考,您還可以使用分解()從 中刪除所有script元素html,即:
soup = BeautifulSoup(html, "html.parser")
# remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
print(soup.find("span", {"class": "age"}).text.strip())
# Ages 15
添加回答
舉報