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

2024-09-28 22:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

<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中,第一行应该是属性标记的名称值,如果属性的标记的可搜索的值为“”,那么这些“限定的”属性标记的父标记-标记名称值。在

目前,我只能找到所有标记的名称值,如果其子项的可搜索值为“是”,但无法将它们归类到相应的属性标记的名称值下。以下是我的初始代码:

^{pr2}$

我也会设法解决这个问题,但为了使过程更快,如果你有任何想法,请提出建议。谢谢您!!在


Tags: noname标记名称属性taginlineattribute
1条回答
网友
1楼 · 发布于 2024-09-28 22:32:28

您的代码找不到任何内容,如果您打印AttrYES,它将是[]。问题是,当您将bs4与解析器lxml一起使用时,所有标记和属性名都将转换为小写,请参考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>

因此,您可以这样修改代码:

^{pr2}$

打印内容为:

^{3}$

然后您可以将它们写入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")

相关问题 更多 >