我在python中使用了漂亮的汤,并且希望从包含在特定标记中的字符串中移除所有的东西,并且有一个带有特定文本的特定非关闭标记。在本例中,我希望删除在其中包含带有DOCA文本的类型标记的所有文档。
假设我有这样的东西:
<body>
<document>
<type>DOCA
<sequence>1
<filename>DOCA.htm
<description>FORM DOCA
<text>
<title>Form DOCA</title>
<h5 align="left"><a href="#toc">Table of Contents</a></h5>
</document>
<document>
<type>DOCB
<sequence>1
<filename>DOCB.htm
<description>FORM DOCB
<text>
<title>Form DOCB</title>
<h5 align="left"><a href="#toc">Table of Contents</a></h5>
</document>
<body>我要做的是删除所有具有<type> of DOCA的。我试过以下几种方法,但不起作用:
>>print(soup.find('document').find('type', text = re.compile('DOCA.*')))
None发布于 2017-07-07 15:14:34
您可以查询所有文档,然后在每个文档中查询所有类型,检查其中是否存在DOCA,如果存在,则删除整个封闭文档。
from bs4 import BeautifulSoup
soup = BeautifulSoup(..., 'html.parser')
for doc in soup.find_all('document'):
for type in doc.find_all('type'):
if 'DOCA' in type.text:
doc.extract()
break
print(soup)输出:
<body>
<document>
<type>DOCB
<sequence>1
<filename>DOCB.htm
<description>FORM DOCB
<text>
<title>Form DOCB</title>
<h5 align="left"><a href="#toc">Table of Contents</a></h5>
</text></description></filename></sequence></type></document>
</body>发布于 2017-07-07 15:31:37
您可以在lambda方法中使用find来选择一个元素,例如:
soup.find('document').find(lambda tag : tag.name == 'type' and 'DOCA' in tag.text) 然后可以使用extract或decompose删除该元素。
编辑:使用此表达式选择所有元素:
soup.find_all(lambda tag:tag.name == 'document'
and tag.find(lambda t:t.name == 'type' and 'DOCA' in t.text))https://stackoverflow.com/questions/44974073
复制相似问题