Skip to main content
 首页 » 编程设计

python之BeautifulSoup : getting contents of all tag> in xml-ish file

2024年10月24日998°冷暖

我有一个 xml-ish 文件,我正在尝试使用 BeautifulSoup 进行解析,假设在另一个标签的树中有多个未知的标签。事情进展顺利,至少对于我在下一个标签集中提取的第一个标签而言。这不是真正的 html 或 xml,但接近...

给定格式:

<data> 
<type> 
    <type_attribute_1>1</type_attribute_1> 
    <type_attribute_2>2</type_attribute_2> 
</type> 
<type> 
    <type_attribute_1>3</type_attribute_1> 
    <type_attribute_2>4</type_attribute_2> 
</type> 
</data> 

我如何为两个类型标签提取 type_attribute_1 和 type_attribute_2 的值并分配给一个变量——即“Type_1_attribute_1”、“Type_1_attribute_2”、“Type_2_attribute_1”和“Type_2_attribute_2”

我正在使用这样的代码,但它只适用于第一个 <type>位于 <data> 内:

Type_1_Attribute_1 = soup.data.type.type_attribute_1.text 
Type_1_Attribute_2 = soup.data.type.type_attribute_2.text 

更新

我认为用稍微不同的方式表达我正在寻找的内容可能会有所帮助。与其声明变量名称 Type_1_Attribute_1,因为我不知道有多少 Type sibling ,而是将“_1”、“_2”、“_3”...添加到“Type”,对于每个 sibling 。即
假设:

Types = [i.stripText() for i in soup.select('Type')] 
parseables = len(Types) 
for i in range(0, parseables) 
    j = i+1 
    Type = Types[i] 
    Attribute_1 = Type.Type_Attribute_1.text  
    print Attribute_1 

它为每个类型打印 Attribute_1 的值,我如何在 Attribute_1 中添加“Type_j”以填充 j 的值?

请您参考如下方法:

这个呢-

from bs4 import BeautifulSoup as bs 
 
data  = """<data> 
<type> 
    <type_attribute_1>1</type_attribute_1> 
    <type_attribute_2>2<2/type_attribute_2> 
</type> 
<type> 
    <type_attribute_1>3</type_attribute_1> 
    <type_attribute_2>4</type_attribute_2> 
</type> 
</data>""" 
 
soup = bs(data,'lxml') 
 
Type_1_Attribute_1 = [i.text.strip() for i in soup.select('type_attribute_1')] 
Type_1_Attribute_2 = [i.text.strip() for i in soup.select('type_attribute_2')] 
 
print filter(bool,Type_1_Attribute_1) 
print filter(bool,Type_1_Attribute_2) 

输出-

[u'1', u'3'] 
[u'2', u'4'] 

编辑 我不明白你为什么需要这个循环遍历列表本身的变量(迭代器) - 例如

for i in Type_1_Attribute_1: 
    print (i)# here i itself a variable and it changes when i reiterate 

打印-

1 
3 

因此,如果您需要使用该列表中的每一项,只需使用迭代器并传递给函数,就像我传递给 print 函数一样。