下载维基百科页面的完整历史记录

Jef*_*son 5 python wikipedia web-scraping

我想下载维基百科上一篇文章的完整修订历史记录,但遇到了障碍。

下载整篇维基百科文章,或者使用Special:Export URL 参数获取其历史片段非常容易:

curl -d "" 'https://en.wikipedia.org/w/index.php?title=Special:Export&pages=Stack_Overflow&limit=1000&offset=1' -o "StackOverflow.xml"
Run Code Online (Sandbox Code Playgroud)

当然,我可以从这里下载整个网站,包括每篇文章的所有版本,但这比我需要的要多 TB 和更多的数据。

有没有预先构建的方法来执行此操作?(看来一定有。)

小智 6

上面的示例仅获取有关修订的信息,而不是实际内容本身。下面是一个简短的 Python 脚本,它将页面的完整内容和元数据历史数据下载到单独的 json 文件中:

import mwclient
import json
import time

site = mwclient.Site('en.wikipedia.org')
page = site.pages['Wikipedia']

for i, (info, content) in enumerate(zip(page.revisions(), page.revisions(prop='content'))):
    info['timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%S", info['timestamp'])
    print(i, info['timestamp'])
    open("%s.json" % info['timestamp'], "w").write(json.dumps(
        { 'info': info,
            'content': content}, indent=4))
Run Code Online (Sandbox Code Playgroud)


Bil*_*ell 4

漫无目的地闲逛寻找另一个问题的线索,我自己 \xe2\x80\x94 我的方式是说我对这个话题一无所知!\xe2\x80\x94 我在读完你的问题后不久就发现了这个:http://mwclient.readthedocs.io/en/latest/reference/page.html。看看revisions方法吧。

\n

编辑:我还看到http://mwclient.readthedocs.io/en/latest/user/page-ops.html#listing-page-revisions

\n

使用该mwclient模块的示例代码:

\n
#!/usr/bin/env python3\nimport logging, mwclient, pickle, os\nfrom mwclient import Site\nfrom mwclient.page import Page\nlogging.root.setLevel(logging.DEBUG)\n\nlogging.debug(\'getting page...\')\nenv_page = os.getenv("MEDIAWIKI_PAGE")\npage_name = env_page is not None and env_page or \'Stack Overflow\'\npage_name = Page.normalize_title(env_page)\nsite = Site(\'en.wikipedia.org\') # https by default. change w/`scheme=`\npage = site.pages[page_name]\n\nlogging.debug(\'extracting revisions (may take a really long time, depending on the page)...\')\nrevisions = []\nfor i, revision in enumerate(page.revisions()):\n    revisions.append(revision)\n\nlogging.debug(\'saving to file...\')\nwith open(\'{}Revisions.mediawiki.pkl\'.format(page_name), \'wb+\') as f:\n    pickle.dump(revisions, f, protocol=0) # protocol allows backwards compatibility between machines\n
Run Code Online (Sandbox Code Playgroud)\n