当父标记的子元素具有某些属性值时,如何使用BeautifulSoup获取父标记的名称值?

时间:2017-05-10 11:17:53

标签: python xml beautifulsoup attributes tags

为了使这个问题更容易理解,下面是一个例子

<Tag name="Thumbnail" inline="no" nonsearchable="yes">
<Attribute>
<Attribute name="AText" Searchable="yes"></Attribute>
</Attribute>
</Tag>

<Tag name="Label" inline="no" nonsearchable="yes">
<Attribute>
<Attribute name="AText" Searchable="no"></Attribute>
</Attribute>
</Tag>

<Tag name="Image" inline="no" nonsearchable="yes">
<Attribute>
<Attribute name="BText" Searchable="yes">
</Attribute>
</Tag>

<Tag name="Wonder" inline="no" nonsearchable="yes">
<Attribute>
<Attribute name="BText" Searchable="yes"></Attribute>
</Attribute>
</Tag>

预期结果

enter image description here

因此,在Excel中,如果属性标记&#39,则第一行应为属性标记的名称值 ; 可搜索值为&#34; &#34 ;;然后这些&#34;合格&#34; 属性标记的父标记 - 标记 - 名称值将列在下面。

目前,我只能找到所有标记的名称值,如果它的子女的可搜索值是&#34;是&#34;,但是无法在相应的属性标记的名称值下对它们进行分类。以下是我的初始代码:

import os, openpyxl
from bs4 import BeautifulSoup

cwd = os.getcwd()

def func(x):
    for file in os.listdir(cwd):
        if file.endswith('.xml'):
            f = open(file, encoding = 'utf=8', mode = 'r+')
            soup = BeautifulSoup(f, 'lxml')
            AttrYES = soup.find_all(attrs={"Searchable": "yes"})
            for items in AttrYES:
                tagName = items.parent.parent.get('name')
                print (tagName)

x = os.listdir(cwd)
func(x)

我也会尝试解决这个问题,但为了让这个过程更快,如果您有任何想法,请提供建议。谢谢!!

1 个答案:

答案 0 :(得分:3)

您的代码找不到任何内容,如果您打印AttrYES,则代码为[]。问题是,当您将bs4与解析器lxml一起使用时,所有标记和attr名称都将转换为小写,请参阅official doc。如果你打印汤,它会给你:

<html><body><tag inline="no" name="Thumbnail" nonsearchable="yes">
<attribute>
<attribute name="AText" searchable="yes"></attribute>
</attribute>
</tag>
<tag inline="no" name="Label" nonsearchable="yes">
<attribute>
<attribute name="AText" searchable="no"></attribute>
</attribute>
</tag>
<tag inline="no" name="Image" nonsearchable="yes">
<attribute>
<attribute name="BText" searchable="yes">
</attribute>
</attribute></tag>
<tag inline="no" name="Wonder" nonsearchable="yes">
<attribute>
<attribute name="BText" searchable="yes"></attribute>
</attribute>
</tag></body></html>

因此,你可以修改你的代码:

import bs4
f = open('test.xml',mode = 'r+')
soup = bs4.BeautifulSoup(f, 'lxml')
AttrYES = soup.findAll(attrs={'searchable': 'yes'})
result = dict()
for items in AttrYES:
    result[items.get('name')] = result.get(items.get('name'),[])+[items.parent.parent.get('name')]    
print(result)

打印将是:

{'AText': ['Thumbnail'], 'BText': ['Image', 'Wonder']}

然后你可以把它们写到excel文件中:

import xlsxwriter

workbook = xlsxwriter.Workbook('result.xlsx')
worksheet = workbook.add_worksheet()

# Write header
worksheet.write(0, 0, result.keys()[0])
worksheet.write(0, 1, result.keys()[1])

# Write data.
worksheet.write_column(1, 0, result.values()[0])
worksheet.write_column(1, 1, result.values()[1])

workbook.close()

result.xlsx将是:

enter image description here

使用openpyxl

更新:

from openpyxl import Workbook
wb = Workbook()

# grab the active worksheet
ws = wb.active

# Data can be assigned directly to cells
i,j = 1,1
for keys,values in a.items():
    ws.cell(column=i, row=1, value=keys)
    for row in range(len(values)):
        ws.cell(column=i, row=j+1, value=values[row])
        j+=1
    j=1
    i+=1
wb.save("result.xlsx")
相关问题