我有以下项目来查找段落中的文本:
soup.find("td", { "id" : "overview-top" }).find("p", { "itemprop" : "description" }).text
我如何排除 <a>
中的所有文本?标签?类似于 in <p> but not in <a>
?
最佳答案
查找并加入所有text nodes在 p
标签中检查它的父标签是否不是 a
标签:
p = soup.find("td", {"id": "overview-top"}).find("p", {"itemprop": "description"})
print ''.join(text for text in p.find_all(text=True)
if text.parent.name != "a")
演示(未看到打印的链接文本
):
>>> from bs4 import BeautifulSoup
>>>
>>> data = """
... <td id="overview-top">
... <p itemprop="description">
... text1
... <a href="google.com">link text</a>
... text2
... </p>
... </td>
... """
>>> soup = BeautifulSoup(data)
>>> p = soup.find("td", {"id": "overview-top"}).find("p", {"itemprop": "description"})
>>> print p.text
text1
link text
text2
>>>
>>> print ''.join(text for text in p.find_all(text=True) if text.parent.name != "a")
text1
text2
关于python - BeautifulSoup 排除特定标签内的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610221/