Wikipediaリンク作成スクリプト
Wikipediaに限ったものでは無い、文字列をUTF-8にエンコードして処理するためのスクリプト。
$ ./wikilink.py インフルエンザ http://ja.wikipedia.org/wiki/%E3%82%A4%E3%83%B3%E3%83%95%E3%83%AB%E3%82%A8%E3%83%B3%E3%82%B6
import sys, urllib plat_cod = sys.getfilesystemencoding() keyword = unicode(sys.argv[1], plat_cod, 'replace').encode('utf-8') url = 'http://ja.wikipedia.org/wiki/' + urllib.quote(keyword) print url
さて、存在しないキーワードを入力した場合、どうするか。
何もせずにurlopenすると
print urllib.urlopen(url).read()
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> <TITLE>ERROR: The requested URL could not be retrieved</TITLE> <STYLE type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></STYLE> </HEAD><BODY> <H1>ERROR</H1> <H2>The requested URL could not be retrieved</H2> <HR noshade size="1px"> <P> While trying to retrieve the URL: <A HREF="http://ja.wikipedia.org/wiki/%E3%82%A4%E3%83%B3%E3%83%95%E3%83%AB%E3%82%A8%E3%83%B3%E3%82%B6">http://ja.wikipedia.org/wiki/%E3%82%A4%E3%83%B3%E3%83%95%E3%83%AB%E3%82%A8%E3%83%B3%E3%82%B6</A> <P> The following error was encountered: <UL> <LI> <STRONG> Access Denied. </STRONG> <P> Access control configuration prevents your request from being allowed at this time. Please contact your service provider if you feel this is incorrect. </UL> <P>Your cache administrator is <A HREF="mailto:wikidown@bomis.com">wikidown@bomis.com</A>. <BR clear="all"> <HR noshade size="1px"> <ADDRESS> Generated Sun, 05 Mar 2006 06:46:09 GMT by yf1000.yaseo.wikimedia.org (squid/2.5.STABLE12) </ADDRESS> </BODY></HTML>
アチャー。
ローカルに保存したデータベースを参照させるのも1つの手。