我想在 XML 檔案中拆分一些多值屬性。
以下是最新報告的內容:
<GenericItem html='ID: AAA1<br/>Age: 12<br/>Name: Baryk <'>
Employee:
</GenericItem>
<GenericItem html='ID: AAA2<br/>Age: 16<br/>Name: Nils <'>
Employee:
</GenericItem>
<GenericItem html='ID: AAA3<br/>Age: 18<br/>Name: Sarah <'>
Employee:
</GenericItem>
這是我的 python 腳本的內容:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('NewestReport.xml', 'r'), 'lxml-xml')
br = soup.find_all("GenericItem")
for i in br:
for i in soup.find("GenericItem").get("html").split("<br/>"):
print(i.split(":")[1].replace("<", "").strip())
使用這種語法,我收到了相同的值,因此它只列印出 Baryk 的值,其余的都不列印。有什么我可以修復的,以便它移動到下一個資料?
uj5u.com熱心網友回復:
您的代碼有兩個主要問題
- 您在
i第二個回圈中覆寫了第一個回圈的值 - 您
find("GenericItem")每次都在呼叫,而不僅僅是使用您之前保存在br變數中的結果
我認為只要像這樣修復它,它就可以達到您的期望
from bs4 import BeautifulSoup
document = BeautifulSoup(open('NewestReport.xml', 'r'), 'lxml-xml')
items = soup.find_all("GenericItem")
for item in items:
for line in item.get("html").split("<br/>"):
print(line.split(":")[1].replace("<", "").strip())
盡管如果您更清楚自己要實作的目標,我們可能會為您提供更好的建議,說明如何解決這個問題
檔案鏈接:
- https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all
uj5u.com熱心網友回復:
注意 正如 Alex Viscreanu 所提到的,您的代碼首先需要處理一些事情。
我建議使用lxml決議器并css selectors選擇元素 - 以下迭代將列印每個元素的所有值GenericItem:
for i in soup.select("GenericItem"):
for e in i.get("html").split("<br/>"):
print(e.split(":")[1].replace("<", "").strip())
--->
AAA1
12
Baryk
AAA2
16
Nils
AAA3
18
Sarah
要獲得更多結構化資料,您可以創建一個字典串列:
data = []
for i in soup.select("GenericItem"):
t={}
for d in i.get("html").split("<br/>"):
info=d.split(":")
k=info[0]
v=info[1].strip(' |<')
t[k]=v
data.append(t)
例子
from bs4 import BeautifulSoup
xml="""<GenericItem html='ID: AAA1<br/>Age: 12<br/>Name: Baryk <'>
Employee:
</GenericItem>
<GenericItem html='ID: AAA2<br/>Age: 16<br/>Name: Nils <'>
Employee:
</GenericItem>
<GenericItem html='ID: AAA3<br/>Age: 18<br/>Name: Sarah <'>
Employee:
</GenericItem>"""
soup = BeautifulSoup(xml, 'lxml')
data = []
for i in soup.select("GenericItem"):
t={}
for d in i.get("html").split("<br/>"):
info=d.split(":")
k=info[0]
v=info[1].strip(' |<')
t[k]=v
data.append(t)
data
輸出
[{'ID': 'AAA1', 'Age': '12', 'Name': 'Baryk'},
{'ID': 'AAA2', 'Age': '16', 'Name': 'Nils'},
{'ID': 'AAA3', 'Age': '18', 'Name': 'Sarah'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380722.html
