我正在嘗試從世界銀行收集資訊。特別是來自本網站的資料。
https://microdata.worldbank.org/index.php/catalog/3761/get-microdata
“DDI/XML”鏈接包含此資料集背后的元資料。如果你下載 DDI/XML 檔案,然后搜索“a3_1”,你會注意到標簽“qstnLit”下的資料有重要資訊被注釋掉了,例如:
“[CDATA[請確定您認為以下哪些是越南最重要的發展優先事項。(選擇不超過三個)-食品安全]]”
我似乎無法收集此資訊:我的代碼如下
from bs4 import BeautifulSoup
file = "VNM_2020_WBCS_v01_M.xml"
import pandas as pd
with open(file, "r", encoding = "utf-8") as f:
sauce = f.read()
soup = BeautifulSoup(sauce, features = "lxml")
ref = pd.DataFrame()
soup = soup.select("codeBook")[0].select("dataDscr")[0].select("var")
for txt in soup:
try:
part = pd.DataFrame(data = {"ID" : [txt.attrs["name"]],
"Qn" : [txt.find("qstn").find("qstnlit").text],
"Lbl" : [txt.find("labl").text],
"Max" : [txt.find(attrs = {"type":"max"}).text],
"Min" : [txt.find(attrs = {"type":"min"}).text]
})
ref = ref.append(part)
except:
pass
我可以拿起未注釋掉的文本,但沒有評論過的文本
有沒有辦法識別評論?
uj5u.com熱心網友回復:
我認為您的問題與您在問題中描述的問題不同。如果我按照撰寫的方式運行您的代碼,它會列印以下警告:
/usr/lib/python3.10/site-packages/bs4/builder/init .py :545:XMLParsedAsHTMLWarning:看起來您正在使用 HTML 決議器決議 XML 檔案。如果這確實是一個 HTML 檔案(可能是 XHTML?),您可以忽略或過濾此警告。如果是 XML,您應該知道使用 XML 決議器會更可靠。要將此檔案決議為 XML,請確保已安裝 lxml 包,并將關鍵字引數傳遞給
features="xml"BeautifulSoup 建構式。
并且不產生任何輸出(那么我們如何判斷它是否有效?)。
如果我們修改代碼以解決該警告:
with open(file, "r", encoding="utf-8") as f:
sauce = f.read()
soup = BeautifulSoup(sauce, features="xml")
并擺脫except你永遠不應該使用的空白,以便 for 回圈看起來像這樣:
for txt in soup:
part = pd.DataFrame(
data={
"ID": [txt.attrs["name"]],
"Qn": [txt.find("qstn").find("qstnlit").text],
"Lbl": [txt.find("labl").text],
"Max": [txt.find(attrs={"type": "max"}).text],
"Min": [txt.find(attrs={"type": "min"}).text],
}
)
ref = ref.append(part)
我們看到它像這樣失敗:
Traceback (most recent call last):
File "/home/lars/tmp/python/souptest.py", line 17, in <module>
"Qn": [txt.find("qstn").find("qstnlit").text],
AttributeError: 'NoneType' object has no attribute 'find'
現在我們看到了有用的資訊!這告訴我們
txt.find('qstn')沒有回傳任何結果,所以也許我們應該檢查一下。
我們在這里看到的第二個問題是您拼錯了qstnLitas
qstnlit,因此我們也需要修復它。
這讓我們:
for txt in soup:
qn = txt.find('qstn')
if not qn:
continue
part = pd.DataFrame(
data={
"ID": [txt.attrs["name"]],
"Qn": [qn.find("qstnLit").text],
"Lbl": [txt.find("labl").text],
"Max": [txt.find(attrs={"type": "max"}).text],
"Min": [txt.find(attrs={"type": "min"}).text],
}
)
ref = ref.append(part)
解決了這些問題后,我們遇到了一個新錯誤:
Traceback (most recent call last):
File "/home/lars/tmp/python/souptest.py", line 23, in <module>
"Min": [txt.find(attrs={"type": "min"}).text],
AttributeError: 'NoneType' object has no attribute 'text'
問題變成了:我們如何處理缺少這些屬性的條目?由于您之前在這些情況下丟棄了整個條目,我們可以通過重新引入
try/except塊來繼續這樣做,現在我們已經解決了圍繞問題文本的問題:
for txt in soup:
try:
part = pd.DataFrame(
data={
"ID": [txt.attrs["name"]],
"Qn": [txt.find("qstn").find("qstnLit").text],
"Lbl": [txt.find("labl").text],
"Max": [txt.find(attrs={"type": "max"}).text],
"Min": [txt.find(attrs={"type": "min"}).text],
}
)
ref = ref.append(part)
except AttributeError:
pass
請注意except,我不是使用空白,而是捕獲我們希望在缺少屬性時收到的特定例外。
此代碼現在運行沒有錯誤。但它有效嗎?ref如果我們在回圈之后列印出來
:
print(ref)
我們似乎找到了一些結果:
ID Qn Lbl Max Min
0 a3_1 \n Please identify which of the follo... \n Food safety\n \n 1\n \n 0\n
0 a3_2 \n Please identify which of the follo... \n Non-communicable disease\n \n 1\n \n 0\n
0 a3_3 \n Please identify which of the follo... \n Gender equity (closing the gap betwe... \n 1\n \n 0\n
0 a3_4 \n Please identify which of the follo... \n Private sector development\n \n 1\n \n 0\n
0 a3_5 \n Please identify which of the follo... \n Education\n \n 1\n \n 0\n
.. ... ... ... ... ...
0 h6_2 \n Which of the following describes m... \n Use World Bank Group reports/data\n ... \n 1\n \n 0\n
0 h6_3 \n Which of the following describes m... \n Engage in World Bank Group related/s... \n 1\n \n 0\n
0 h6_4 \n Which of the following describes m... \n Collaborate as part of my profession... \n 1\n \n 0\n
0 h6_5 \n Which of the following describes m... \n Use World Bank Group website for inf... \n 1\n \n 0\n
0 h8 \n What's your age?\n \n What's your age?\n \n 5\n \n 2\n
[279 rows x 5 columns]
這里的 tl;dr 是您的問題與 CDATA 塊無關。相反,您的try/except塊隱藏了可以幫助您解決問題的錯誤。通過至少暫時洗掉該塊,我們能夠檢測和糾正代碼錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493448.html
上一篇:從XML字串中提取某些部分
