我想写一个python程序,可以搜索维基百科的人的出生和死亡日期。例如,阿尔伯特爱因斯坦1879年3月14日出生;死亡:4月18日1955年解析维基百科的出生和死亡日期?
我开始与Fetch a Wikipedia article with Python
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
infile = opener.open('http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&rvsection=0&titles=Albert_Einstein&format=xml')
page2 = infile.read()
这工作尽可能去。 page2
是来自Albert Einstein维基百科页面的部分的xml表示形式。
我看了这个教程,现在我有了xml格式的页面... http://www.travisglines.com/web-coding/python-xml-parser-tutorial,但我不明白如何从xml中获取我想要的信息(出生和死亡日期)。我觉得我一定要接近,然而,我不知道如何从这里出发。
编辑
经过几次的反应,我已经安装了BeautifulSoup。我现在的阶段,我可以打印:
import BeautifulSoup as BS
soup = BS.BeautifulSoup(page2)
print soup.getText()
{{Infobox scientist
| name = Albert Einstein
| image = Einstein 1921 portrait2.jpg
| caption = Albert Einstein in 1921
| birth_date = {{Birth date|df=yes|1879|3|14}}
| birth_place = [[Ulm]], [[Kingdom of Württemberg]], [[German Empire]]
| death_date = {{Death date and age|df=yes|1955|4|18|1879|3|14}}
| death_place = [[Princeton, New Jersey|Princeton]], New Jersey, United States
| spouse = [[Mileva Marić]]&nbsp;(1903–1919)<br>{{nowrap|[[Elsa Löwenthal]]&nbsp;(1919–1936)}}
| residence = Germany, Italy, Switzerland, Austria, Belgium, United Kingdom, United States
| citizenship = {{Plainlist|
* [[Kingdom of Württemberg|Württemberg/Germany]] (1879–1896)
* [[Statelessness|Stateless]] (1896–1901)
* [[Switzerland]] (1901–1955)
* [[Austria–Hungary|Austria]] (1911–1912)
* [[German Empire|Germany]] (1914–1933)
* United States (1940–1955)
}}
所以,更接近,但我仍然不知道如何在这种格式返回death_date。除非我开始用re
解析东西?我可以做到这一点,但我觉得我会为这项工作使用错误的工具。
XML解析器不会帮你进一步。阅读JBernardo所说的内容:以json格式获取数据并使用专用的MW分析器。 – georg
我附上了完整的代码,并且都使用/不使用're'来解析它。 –
请不要试图通过您的用户代理模拟浏览器。根据[维基媒体用户代理政策](http://meta.wikimedia.org/wiki/User-Agent_policy),您应该使用“带有联系信息的信息性用户代理字符串”。 – svick