【问题标题】:Get same tags with different content from xml with beautifulsoup使用 beautifulsoup 从 xml 中获取具有不同内容的相同标签
【发布时间】:2019-05-08 12:16:38
【问题描述】:

我有这个 xml:

<dc:type>image fixe</dc:type>
<dc:type>image</dc:type>
<dc:type>still image</dc:type>
<dc:type>dessin</dc:type>
<dc:type>drawing</dc:type>

我想要所有“dc:type”标签的所有文本。我可以使用soup.find("dc:type").get_text() 获得第一个,但是当我尝试时,例如:

for i in soup.find_all("dc:type"):
     type = "|".join(i.get_text())

它什么也得不到。仅打印soup.find_all("dc:type") 也一无所获,而仅使用 find 打印似乎还可以。 我做错了什么?

【问题讨论】:

    标签: xml beautifulsoup tags


    【解决方案1】:

    我不知道为什么它不适合你。我有所有的价值观。

    from bs4 import BeautifulSoup
    
    data='''<dc:type>image fixe</dc:type>
    <dc:type>image</dc:type>
    <dc:type>still image</dc:type>
    <dc:type>dessin</dc:type>
    <dc:type>drawing</dc:type>'''
    
    soup=BeautifulSoup(data,'html.parser')
    for item in soup.find_all('dc:type'):
     print(item.text)
    

    输出:

    image fixe
    image
    still image
    dessin
    drawing
    

    您也可以使用 lambda 来搜索标签名称。

    from bs4 import BeautifulSoup
    
    data='''<dc:type>image fixe</dc:type>
    <dc:type>image</dc:type>
    <dc:type>still image</dc:type>
    <dc:type>dessin</dc:type>
    <dc:type>drawing</dc:type>'''
    
    soup=BeautifulSoup(data,'html.parser')
    for item in soup.find_all(lambda tag:tag.name=='dc:type'):
     print(item.text)
    

    【讨论】:

    • 我不知道为什么不这样,我也不知道。这有点令人沮丧。但是使用 lambda 可以工作,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    相关资源
    最近更新 更多