正如其他人所说,一种方法是使用维基媒体API和urllib或urllib2。下面的代码片段是我用来提取所谓的“主角”部分的部分内容,其中包含文章摘要和信息框。这将检查返回的文本是否是重定向而不是实际内容,并且还可以让您跳过信息框(如果存在的话)(在我的情况下,我使用不同的代码提取并格式化信息框。
contentBaseURL='http://en.wikipedia.org/w/index.php?title='
def getContent(title):
URL=contentBaseURL+title+'&action=raw§ion=0'
f=urllib.urlopen(URL)
rawContent=f.read()
return rawContent
infoboxPresent = 0
# Check if a redirect was returned. If so, go to the redirection target
if rawContent.find('#REDIRECT') == 0:
rawContent = getFullContent(title)
# extract the redirection title
# Extract and format the Infobox
redirectStart=rawContent.find('#REDIRECT[[')+11
count = 0
redirectEnd = 0
for i, char in enumerate(rawContent[redirectStart:-1]):
if char == "[": count += 1
if char == "]}":
count -= 1
if count == 0:
redirectEnd = i+redirectStart+1
break
redirectTitle = rawContent[redirectStart:redirectEnd]
print 'redirectTitle is: ',redirectTitle
rawContent = getContent(redirectTitle)
# Skip the Infobox
infoboxStart=rawContent.find("{{Infobox") #Actually starts at the double {'s before "Infobox"
count = 0
infoboxEnd = 0
for i, char in enumerate(rawContent[infoboxStart:-1]):
if char == "{": count += 1
if char == "}":
count -= 1
if count == 0:
infoboxEnd = i+infoboxStart+1
break
if infoboxEnd <> 0:
rawContent = rawContent[infoboxEnd:]
您将找回包含wiki标记的原始文本,因此您需要进行一些清理。如果您只想要第一段,而不是整个第一段,请查找第一个新行字符。
“urllib”用于获取页面,“BeautifulSoup”用于解析HTML。尽管还有其他的方法,但是在StackOverflow本身上搜索它们。这已经被讨论了很多次。 – user225312 2010-12-16 12:54:24
你想要什么标记? mediawiki,html? – khachik 2010-12-16 12:55:49
HTML。 (15个字符的限制) – 2010-12-16 12:59:04