我正在尝试解析维基词典的 XML 转储,但可能我丢失了一些东西,因为我没有得到任何输出。
这是一个类似但短得多的 xml 文件:
<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.8/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.8/ http://www.mediawiki.org/xml/export-0.8.xsd" version="0.8" xml:lang="it">
<page>
<title>bigoto</title>
<ns>0</ns>
<id>24840</id>
<revision>
<id>1171207</id>
<parentid>743817</parentid>
<timestamp>2011-12-18T19:26:42Z</timestamp>
<contributor>
<username>GnuBotmarcoo</username>
<id>14353</id>
</contributor>
<minor />
<comment>[[Wikizionario:Bot|Bot]]: Sostituisco template {{[[Template:in|in]]}}</comment>
<text xml:space="preserve">== wikimarkups ==</text>
<sha1>gji6wqnsy6vi1ro8887t3bikh7nb3fr</sha1>
<model>wikitext</model>
<format>text/x-wiki</format>
</revision>
</page>
</mediawiki>
我有兴趣解析 <title>
的内容元素如果 <ns>
元素等于 0。
这是我的脚本
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
for page in root.findall('page'):
ns = int(page.find('ns').text)
word = page.find('title').text
if ns == 0:
print word
最佳答案
我建议使用 BeautifulSoup
您可以在其中进行类似的操作,因为它非常易于使用。
from bs4 import BeautifulSoup as BS
# given your html as the variable 'html'
soup = BS(html, "xml")
pages = soup.find_all('page')
for page in pages:
if page.ns.text == '0':
print page.title.text
据我所知,无需使用 int
转换您的<ns>
标记为要与 == 0
进行比较的整数。与字符串 '0'
进行比较效果同样好——在这种情况下甚至更容易,因为您根本不需要处理转换。
关于python - 解析 MediaWiki wiki 的 XML 转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16533153/