为了使这个问题更容易理解,下面是一个示例
<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>
预期结果
因此,在excel中,如果Attribute标签的Searchable值为“ yes ” ,则第一行应为Attribute标签的名称值;然后,这些“合格”属性标签的父标签-标签-名称值将下面列出。
目前,我只能找到所有Tag的名称值,如果它们的子级Searchable值为“ yes”,但无法将其归类为相应的Attribute标记的名称值。下面是我的初始代码:
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)
我也会尝试解决这个问题,但是为了使过程更快,如果您有任何想法,请提出建议。谢谢!!
您的代码找不到任何内容,如果您进行打印AttrYES
,它将为[]
。问题是,当bs4
与解析器一起使用时lxml
,所有标记和属性名称都将转换为小写,请参阅官方文档。如果您打印汤,它将为您提供:
<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
会是:
更新:使用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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句