解析MediaWiki wiki的XML转储

时间:2013-05-14 00:13:20

标签: python xml elementtree wiktionary wikimedia-dumps

我正在尝试解析维基词典的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>元素等于0,我有兴趣解析<ns>元素的内容。

这是我的剧本

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

1 个答案:

答案 0 :(得分:1)

我建议您使用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'进行比较同样适用 - 在这种情况下更简单,因为您根本不需要处理转换。

相关问题