Python 美丽的汤在标签中寻找标签

Python 美丽的汤在标签中寻找标签,python,html,unit-testing,beautifulsoup,Python,Html,Unit Testing,Beautifulsoup,我正在尝试创建一个unittest,其中可以在html标记中找到body标记,我尝试进行以下测试,但由于某些原因,我发现语法错误,我已正确设置了Beauty Soup,等等: for tag in soup.find_all(re.compile("""<html.*><body.*></body></html>""")): count+=1 self.assertEqual(count,1) 用于soup.find_all(重新编译)(

我正在尝试创建一个unittest,其中可以在html标记中找到body标记,我尝试进行以下测试,但由于某些原因,我发现语法错误,我已正确设置了Beauty Soup,等等:

for tag in soup.find_all(re.compile("""<html.*><body.*></body></html>""")):
    count+=1
self.assertEqual(count,1)
用于soup.find_all(重新编译)(“”)中的标记的
:
计数+=1
自身资产质量(计数,1)

您可以使用
.parent
属性查看感兴趣标记的父标记是什么:

html = '<html>\
 <head>\
  <title>Test</title>\
 </head>\
 <body>\
  bla\
<a><body></body></a>\
 </body>\
</html>\
<body>\
 bla\
</body>'

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')
bodies = soup.findAll('body')
for body in bodies:
  parent = body.parent.name
  if ( parent == 'html' ):
    print('Good! Parent = ' + body.parent.name)
  else:
    print('Uh oh! Parent = ' + body.parent.name)

为什么会这样?为什么不搜索所有
html
标记,然后检查每个
html
标记内是否有
body
标记?我想做的测试是专门找到body标记在html标记内。