我有一个HTML文件,格式如下:
<div class="entry">
<p>para1</p>
<p><a href="www.site.com">para2</a></p>
<p><div class="abc"> Ignore this part1</div> </p>
<p><script class="xyz">Ignore this part2 </script></p>
</div>
假设只有一个div标签,其类值为“entry”。我想打印div标签内的所有文本,其中包含类值“entry”,除了那些后跟div或script标签的p标签。所以在这里我要打印“para1”和“para2”但不是“忽略这个part1”和“忽略这个part2” 如何使用美丽的汤来实现这一目标?
答案 0 :(得分:0)
使用lambda
表达式来过滤您不需要的内容。
示例:
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
example = """<div class="entry">
<p>para1</p>
<p><a href="www.site.com">para2</a></p>
<p><div class="abc"> Ignore this part1</div> </p>
<p><script class="xyz">Ignore this part2 </script></p>
<p>example para</p>
</div>"""
soup = BeautifulSoup(example, 'html.parser')
entry = soup.find('div', class_="entry")
p = entry.find_all(lambda tag: tag.name == "p" and not (tag.find("div")
or tag.find("script")))
for content in p:
print (content.get_text(strip=True))
输出:
para1
para2
example para