簡體   English   中英

如何在BeautifulSoup中獲取包含自閉標簽的子元素?

[英]How to get children element that contains self closing tag in beautifulsoup?

我在每個div中都有兩個輸入元素(這是自閉標簽),但是我只有一個輸入元素。

這是我的代碼:

from bs4 import BeautifulSoup
from bs4.element import Tag

html_doc = '''<cfform>

<div name="first_div">
  First name:<cfinput type="text" name="firstname">
  Last name:<cfinput type="text" name="lastname">
</div>
<div name="second_div">
  Address:<cfinput type="text" name="address">
  Contact Number:<cfinput type="text" name="contact_number">
</div>

</cfform>'''

soup = BeautifulSoup(html_doc, 'xml')
for div in soup.find_all("div"):
    print(div.get("name"))
    for child in div.children:
        if isinstance(child, Tag):
            print(" ", child.get("name"))

CCO完全正確。 如果您修改<cfinput>標記以指示它們是自動關閉的,則通過添加/<cfinput/> ,您將獲得我們想要看到的輸出。

您的代碼與CCO的建議

from bs4 import BeautifulSoup
from bs4.element import Tag

html_doc = '''<cfform>

<div name="first_div">
  First name:<cfinput type="text" name="firstname"/>
  Last name:<cfinput type="text" name="lastname"/>
</div>
<div name="second_div">
  Address:<cfinput type="text" name="address"/>
  Contact Number:<cfinput type="text" name="contact_number"/>
</div>

</cfform>'''

soup = BeautifulSoup(html_doc, 'xml')
for div in soup.find_all("div"):
    print(div.get("name"))
    for child in div.children:
        if isinstance(child, Tag):
            print(" ", child.get("name"))

運行以上命令后的輸出

first_div
('',u'firstname')
('',u'lastname')
second_div
('','地址')
('',u'contact_number')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM