【问题标题】:BeautifulSoup: get tag name of element itself, not its childrenBeautifulSoup:获取元素本身的标签名称,而不是其子元素
【发布时间】:2012-01-21 22:49:00
【问题描述】:

我有以下(简化的)代码,它使用以下源:

<html>
    <p>line 1</p>
    <div>
        <a>line 2</a>
    </div>
</html>

soup = BeautifulSoup('<html><p>line 1</p><div><a>line 2</a></div></html>')
ele = soup.find('p').nextSibling
somehow_print_tag_of_ele_here

我想得到ele的标签,在本例中是“div”。但是,我似乎只能获得其孩子的标签。我错过了一些简单的东西吗?我以为我可以做 ele.tag.name,但这是一个例外,因为 tag 是 None。

#Below correctly prints the div element "<div><a>line 2</a></div>"
print ele

#Below prints "None". Printing tag.name is an exception since tag is None
print ele.tag 

#Below prints "a", the child of ele
allTags = ele.findAll(True)
for e in allTags:
    print e.name

此时,我正在考虑在获取 ele 的父级的过程中做一些事情,然后获取父级的子级标签,并计算 ele 有多少上兄弟姐妹,倒数到正确的子级标签。这似乎很荒谬。

【问题讨论】:

    标签: tags beautifulsoup


    【解决方案1】:

    打印(soup.find('h1',id_='pdp_product_title')) 它不打印任何细节请解决这个问题

    &lt;h1 id="pdp_product_title" class="headline-2 css-zis9ta" data-test="product-title"&gt;Nike Air Force 1 Shadow&lt;/h1&gt;

    【讨论】:

      【解决方案2】:

      您可以像访问字典一样访问元素内的任何内容。 假设您有一个像这样的元素。

      <input id="__VIEWSTATE3" name="__VIEWSTATE3" type="hidden" value="MwqzeTH4"/>
      

      您可以像这样访问每个属性

      print(elem["id"])
      # prints __VIEWSTATE3
      

      【讨论】:

        【解决方案3】:

        ele 已经是标签了,试试这个:

        soup = BeautifulSoup('<html><p>line 1</p><div><a>line 2</a></div></html>')
        print(soup.find('p').nextSibling.name)
        

        所以在你的例子中它只是

        print(ele.name)
        

        【讨论】:

        • @user984003 看到编辑,我提出了一个例子,但它应该按照你要求的方式工作。重要的部分是你不应该做.tag.name,直接.name
        • 但是,我明白了,我已经有了一个标签,所以我这样做了:打印 ele.name。我对其进行了测试并且它有效:) 我错过了一些简单的东西!如果您将答案编辑为 ele.name,那么我会尽可能将其作为正确答案进行检查。
        • 是否可以在条件中使用ele.name?类似:if ele.name is 'a': 对我不起作用。
        • @zimmi 我可以在没有问题的情况下使用 ele.name,但我确实使用了 ele.name == 'a'。使用is 运算符,您可以使用== 进行身份测试与相等测试。
        • 谢谢!以及如何获取line 2的内容?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-16
        • 2021-12-24
        • 1970-01-01
        • 2019-05-15
        • 2011-07-17
        • 2018-11-19
        相关资源
        最近更新 更多