Skip to main content
 首页 » 编程设计

python之解析 MediaWiki wiki 的 XML 转储

2024年11月01日9freeliver54

我正在尝试解析 Wiktionary 的 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' 进行比较效果一样好——在这种情况下甚至更容易,因为您根本不必处理转换。