如何检查BeautifulSoup标签是否为特定标签?

时间:2019-12-01 17:54:43

标签: python xml beautifulsoup wordprocessingml

如果我使用beautifulsoup找到了某个标签:

styling = paragraphs.find_all('w:rpr')

我看下一个标签。如果它是<w:t>标签,我只想使用该标签。如何检查下一个标签是什么类型的标签?

我尝试了element.find_next_sibling().startswith('<w:t')作为元素,但是显示为NoneType object is not callable。我也尝试过element.find_next_sibling().find_all('<w:t'>),但它没有返回任何内容。

for element in styling:
    next = element.find_next_sibling()
    if(#next is a <w:t> tag):
        ...

我正在使用beautifulsoup,并希望坚持使用它,并且尽可能不使用bs4添加eTree或其他解析器。

1 个答案:

答案 0 :(得分:2)

使用item.name可以看到标签的名称。

问题是标签之间存在元素NavigableString,它们也被视为同级元素,并且给出None

您将不得不跳过这些元素,否则您将获得所有兄弟姐妹,并使用for循环查找第一个<w:t>并使用break退出循环

from bs4 import BeautifulSoup as BS

text = '''<div>
  <w:rpr></w:rpr>
  <w:t>A</w:t>
</div>'''

soup = BS(text, 'html.parser')

all_wrpr = soup.find_all('w:rpr')
for wrpr in all_wrpr:

    next_tag = wrpr.next_sibling
    print('name:', next_tag.name) # None

    next_tag = wrpr.next_sibling.next_sibling
    #next_tag = next_tag.next_sibling
    print('name:', next_tag.name) # w:t
    print('text:', next_tag.text) # A

#name: None
#name: w:t
#text: A

print('---')

all_siblings = wrpr.next_siblings
for item in all_siblings:
    if item.name == 'w:t':
       print('name:', item.name) # w:t
       print('text:', item.text) # A
       break # exit after first <w:t>

#name: w:t
#text: A    

编辑:如果您测试的HTML格式的代码差异不大

text = '''<div>
  <w:rpr></w:rpr><w:t>A</w:t>
</div>'''

然后,标记之间将没有NavigableString,第一种方法将失败,但第二种方法仍将起作用。