【问题标题】:How to get the tag name of html using Python Beautiful Soup?如何使用 Python Beautiful Soup 获取 html 的标签名称?
【发布时间】:2019-04-15 16:55:39
【问题描述】:
header = head.find_all('span')

[<span itemprop="name">Raj</span>, <span itemprop="street">24 Omni  Street</span>, <span itemprop="address">Ohio</span>, <span itemprop="Region">US</span>, <span itemprop="postal">40232</span>, <span class="number">334646344</span>]

print (header[0].tag)
print(header[0].text)

####output
None
Raj
...

####Expected output
Name
Raj
...

我无法提取 span itemprop 的所有值。它让我没有输出。我是不是做错了什么?

谢谢, 拉杰

【问题讨论】:

    标签: python html css beautifulsoup tags


    【解决方案1】:

    是的,class 'bs4.element.Tag' 没有tag 属性,因为它自己一个Tag。来自文档:

    您可以通过将标签视为字典来访问标签的属性。

    所以你已经得到了所有span标签的列表,现在只需迭代列表并获得你想要的属性(即'itemprop'):

    spans = head.find_all('span')
    
    for span in spans:
        try:
            print(span['itemprop'].decode().title() + ': ' + span.text)
        except KeyError:
            continue 
    

    输出:

    Name: Raj
    Street: 24 Omni  Street
    Address: Ohio
    Region: US
    Postal: 40232
    

    根据需要格式化输出或存储数据

    【讨论】:

      猜你喜欢
      • 2016-07-06
      • 1970-01-01
      • 2017-01-17
      • 2019-05-30
      • 2021-02-22
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      相关资源
      最近更新 更多