【问题标题】:Beautiful soup finding tags within tags漂亮的汤在标签中找到标签
【发布时间】:2015-05-03 13:00:46
【问题描述】:

我正在尝试创建一个可以在 html 标记中找到正文标记的单元测试,我尝试进行以下测试,但由于某种原因我看到语法错误,我已经正确设置了 Beautiful Soup,等:

for tag in soup.find_all(re.compile("""<html.*><body.*></body></html>""")):
    count+=1
self.assertEqual(count,1)

【问题讨论】:

  • 为什么会这样?为什么不直接搜索所有html 标签,然后检查每个html 标签内是否有body 标签?
  • 好吧,我要做的测试是专门发现body标签在html标签内。

标签: python html unit-testing beautifulsoup


【解决方案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)

示例文档包含一个&lt;body&gt; 标签,它是&lt;html&gt; 标签的子标签,一个嵌套在其他标签中,一个完全在文档之外。输出是这样的:

Good! Parent = html
Uh oh! Parent = a
Uh oh! Parent = [document]

【讨论】:

    猜你喜欢
    • 2012-12-27
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2019-09-06
    • 2020-03-15
    相关资源
    最近更新 更多