【发布时间】:2019-06-29 18:28:24
【问题描述】:
我正在使用 BeautifulSoup 4 和 python 来解析一些 HTML。代码如下:
from bs4 import BeautifulSoup as bs
html_doc = '<p class="line-spacing-double" align="center">IN <i>THE </i><b>DISTRICT</b> COURT OF {county} COUNTY\nSTATE OF OKLAHOMA</p>'
soup = bs(html_doc, 'html.parser')
para = soup.p
for child in soup.p.children:
print (child)
结果是:
IN
<i>THE </i>
<b>DISTRICT</b>
COURT OF {county} COUNTY
STATE OF OKLAHOMA
这一切都说得通。我想要做的是遍历结果,如果我找到<i> 或<b> 然后对它们做一些不同的事情。当我尝试以下操作时,它不起作用:
for child in soup.p.children:
if child.findChildren('i'):
print('italics found')
错误是因为第一个返回的孩子是一个字符串,我正在尝试搜索一个孩子标签,而 BS4 已经知道没有孩子在场。
所以我修改了代码来检查孩子是否是一个字符串,如果是,不要尝试对其采取任何操作,只需将其打印出来。
for child in soup.p.children:
if isinstance(child, str):
print(child)
elif child.findAll('i'):
for tag in child.findAll('i'):
print(tag)
这个最新代码的结果:
IN
COURT OF {county} COUNTY
STATE OF OKLAHOMA
当我遍历结果时,我需要能够检查结果中的标签,但我似乎无法弄清楚如何。我认为这应该很简单,但我很难过。
编辑:
回应 jacalvo:
如果我跑步
for child in soup.p.children:
if child.find('i'):
print(child)
仍然无法从 HTML 代码中打印出第 2 行和第 3 行
编辑:
for child in soup.p.children:
if isinstance(child, str):
print(child)
else:
print(child.findChildren('i', recursive=False))
这导致:
IN
[]
[]
COURT OF {county} COUNTY
STATE OF OKLAHOMA
【问题讨论】:
-
用
find('i')代替findChildren()怎么样? -
p = soup.select_one('p')然后p.select('i, b') -
jacalvo - 我需要编写代码(这在 cmets 中很烂),所以我通过对原始帖子的编辑回复了您。
-
@Andrej Kesely - 这适用于查找
<i>和<b>标签,但我确实需要遍历所有标签,而不仅仅是找到这些标签。它们在 HTML 中的位置对我需要做的事情很重要。
标签: python beautifulsoup