考虑这个XML文件:
-
Apple
2.99
-
Banana
1.99
我们可以使用正则表达式来匹配连字符标签的子元素(即item-name和item-price):
import re
from bs4 import BeautifulSoup
xml = """
-
Apple
2.99
-
Banana
1.99
"""
soup = BeautifulSoup(xml, "xml")
# 使用正则表达式匹配带连字符的标签
pattern = re.compile(r'(\w+)-(\w+)')
items = soup.find_all(pattern)
# 打印结果
for item in items:
print(item.name, item.text)
输出结果为:
item-name Apple
item-price 2.99
item-name Banana
item-price 1.99