您可以使用MySQLdb 模块在不使用 HTTP 和 cookie 的情况下连接和修改 SQL 数据库,但这通常是进行 MediaWiki 维护的错误解决方案。虽然只读访问应该不是问题。
使用脚本访问 MediaWiki 的最佳方式是使用 api.php。
最著名的基于 Python 的 MediaWiki-API-bot 是 Pywikibot(以前的 Pywikipediabot)。
在 Python 中保存 cookie 的最简单方法可能是使用 http.cookiejar 模块。
它的文档包含一些简单的示例。
我从自己的 MediaWiki-bot 中提取了功能示例代码:
#!/usr/bin/python3
import http.cookiejar
import urllib.request
import urllib.parse
import json
s_login_name = 'example'
s_login_password = 'secret'
s_api_url = 'http://en.wikipedia.org/w/api.php'
s_user_agent = 'StackOverflowExample/0.0.1.2012.09.26.1'
def api_request(d_post_params):
d_post_params['format'] = 'json'
r_post_params = urllib.parse.urlencode(d_post_params).encode('utf-8')
o_url_request = urllib.request.Request(s_api_url, r_post_params)
o_url_request.add_header('User-Agent', s_user_agent)
o_http_response = o_url_opener.open(o_url_request)
s_reply = o_http_response.read().decode('utf-8')
d_reply = json.loads(s_reply)
return (o_http_response.code, d_reply)
o_cookie_jar = http.cookiejar.CookieJar()
o_http_cookie_processor = urllib.request.HTTPCookieProcessor(o_cookie_jar)
o_url_opener = urllib.request.build_opener(o_http_cookie_processor)
d_post_params = {'action': 'login', 'lgname': s_login_name}
i_code, d_reply = api_request(d_post_params)
print('http code: %d' % (i_code))
print('api reply: %s' % (d_reply))
s_login_token = d_reply['login']['token']
d_post_params = {
'action': 'login',
'lgname': s_login_name,
'lgpassword': s_login_password,
'lgtoken':s_login_token
}
i_code, d_reply = api_request(d_post_params)
print('http code: %d' % (i_code))
print('api reply: %s' % (d_reply))
类、错误处理和子函数已被移除以增加可读性。
o_url_opener 中保存的 cookie 也可用于对index.php 的请求。
您也可以通过 index.php 登录(伪造浏览器请求),但这将包括 HTML 输出的解析。
变量名图例:
# Unicode string
s_* = 'a'
# Bytes (raw string)
r_* = b'a'
# Dictionary
d_* = {'a':1}
# Integer number
i_* = 4711
# Other objects
o_* = SomeClass()