![]() |
ノート/テキストマイニング/Bing検索https://pepper.is.sci.toho-u.ac.jp:443/pepper/index.php?%A5%CE%A1%BC%A5%C8%2F%A5%C6%A5%AD%A5%B9%A5%C8%A5%DE%A5%A4%A5%CB%A5%F3%A5%B0%2FBing%B8%A1%BA%F7 |
![]() |
追加の情報として
戻ってきたXMLデータの解析については
Bingからの応答では、
xmlns="http://schemas.microsoft.com/LiveSearch/2008/04/XML/element" Version="2.2"
が使われている。XMLのName Spaceである。これはExpatで処理できる。
#!/usr/bin/env python # -*- coding: utf-8 import sys import glob import codecs import urllib import xml.parsers.expat sys.stdout = codecs.getwriter('utf_8')(sys.stdout) # 3 handler functions def start_element(name, attrs): global StartURL ### <-- Absolutely necessary [a1,a2] = name.split(' ') if (a1 == 'http://schemas.microsoft.com/LiveSearch/2008/04/XML/web'): print 'Start %s'.encode('utf-8') % a2.encode('utf-8') if (a2 == 'Url'): # print '>>> StartURL %s' % StartURL StartURL = 1 # print '>>> StartURL %s' % StartURL else: print 'Start %s'.encode('utf-8') % name.encode('utf-8') ##for (key, val) in attrs.iteritems(): ## print 'attribute: %s = %s'.encode('utf-8') % (key.encode('utf-8'), val.encode('utf-8')) def end_element(name): global StartURL ### <-- Absolutely necessary [a1,a2] = name.split(' ') # "name" contains "http://.../XML/web ****" where **** is like "Url", so split them by a space. if (a1 == 'http://schemas.microsoft.com/LiveSearch/2008/04/XML/web'): print 'End %s'.encode('utf-8') % a2.encode('utf-8') if (a2 == 'Url'): # print '>>> EndURL %s' % StartURL StartURL = 0 # print '>>> EndURL %s' % StartURL else: print 'End %s'.encode('utf-8') % name.encode('utf-8') def char_data(data): global StartURL, URLlist ## <-- Absolutely Necessary # print 'Data:', data # print '>>> StartURLvalue %s' % StartURL if (StartURL == 1): # print '>>> WithinURL. Saving %s' % data.encode('utf-8') URLlist.append(data) #p = xml.parsers.expat.ParserCreate() p = xml.parsers.expat.ParserCreate("utf-8"," ") p.returns_unicode=1 p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data URLlist = [] contents = [] StartURL = 0 f = open('OS_kernel.txt') p.ParseFile(f) print URLlist f = urllib.urlopen(URLlist[0]) # Access the 1st element only. result = f.read() print '======' print URLlist[0] print '======' print result
上記で得られた Url フィールド
<web:Url>http://ja.wikipedia.org/wiki/%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%AB</web:Url>
に書かれたURLを切り出して、実際のページにアクセスする。
具体的には、(この例の様に)ウィキペディアをアクセスする可能性が高い。ところが、ウィキペディアを urllibのurlopenでアクセスすると、サーバーエラーを返してくる。正確な原因は分からないが、可能性があるのは、クライアントタイプがブラウザで無いこと、である。そこで、アクセス時のヘッダーに、クライアントタイプを入れてみる。
その方法として、urllib2には、openerという道具があって
url = "http://ja.wikipedia.org/wiki/%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%AB" opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] f2 = opener.open(url) result = f2.read()
のようにすることができる。
これによって、ウィキペディアにアクセスできる。
次の問題として、ウィキペディアから得られた情報から、本文を取り出す必要がある。 データ例は
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="ja" dir="ltr"> <head> <title>カーネル - Wikipedia</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <meta name="generator" content="MediaWiki 1.16wmf4" /> <link rel="alternate" type="application/x-wiki" title="編集" href="/w/index.php?title=%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%AB&action=edit" /> <link rel="edit" title="編集" href="/w/index.php?title=%E3%82%AB%E3%83%BC%E3%83 %8D%E3%83%AB&action=edit" /> <link rel="apple-touch-icon" href="http://ja.wikipedia.org/apple-touch-icon.png" /> <link rel="shortcut icon" href="/favicon.ico" /> <link rel="search" type="application/opensearchdescription+xml" href="/w/opensearch_desc.php" title="Wikipedia (ja)" /> <link rel="copyright" href="http://creativecommons.org/licenses/by-sa/3.0/" /> <link rel="alternate" type="application/atom+xml" title="Wikipedia Atomフィード" href="/w/index.php?title=%E7%89%B9%E5%88%A5:%E6%9C%80%E8%BF%91%E3%81%AE%E6 %9B%B4%E6%96%B0&feed=atom" /> <link rel="stylesheet" href="http://bits.wikimedia.org/skins-1.5/common/shared.css?276z56" type="text/css" media="screen" /> <link rel="stylesheet" href="http://bits.wikimedia.org/skins-1.5/common/commonPrint.css?276z56" type="text/css" media="print" /> <link rel="stylesheet" href="http://bits.wikimedia.org/skins-1.5/monobook/main.css?276z56" type="text/css" media="screen" /> <link rel="stylesheet" href="http://bits.wikimedia.org/skins-1.5/chick/main.css?276z56" type="text/css" media="handheld" /> <!--[if lt IE 5.5000]><link rel="stylesheet" href="http://bits.wikimedia.org /skins-1.5/monobook/IE50Fixes.css?276z56" type="text/css" media="screen" /><![endif]--> <!--[if IE 5.5000]><link rel="stylesheet" href="http://bits.wikimedia.org /skins-1.5/monobook/IE55Fixes.css?276z56" type="text/css" media="screen" /><![endif]--> <!--[if IE 6]><link rel="stylesheet" href="http://bits.wikimedia.org/skins- 1.5/monobook/IE60Fixes.css?276z56" type="text/css" media="screen" /><![endif]--> <!--[if IE 7]><link rel="stylesheet" href="http://bits.wikimedia.org/skins- 1.5/monobook/IE70Fixes.css?276z56" type="text/css" media="screen" /><![endif]--> <link rel="stylesheet" href="/w/index.php?title=MediaWiki:Common.css& usemsgcache=yes&ctype=text%2Fcss&smaxage=2678400&action=raw& maxage=2678400" type="text/css" media="all" /> <link rel="stylesheet" href="/w/index.php?title=MediaWiki:Print.css& usemsgcache=yes&ctype=text%2Fcss&smaxage=2678400&action=raw& maxage=2678400" type="text/css" media="print" /> <link rel="stylesheet" href="/w/index.php?title=MediaWiki:Handheld.css& usemsgcache=yes&ctype=text%2Fcss&smaxage=2678400&action=raw& maxage=2678400" type="text/css" media="handheld" /> <link rel="stylesheet" href="/w/index.php?title=MediaWiki:Monobook.css& usemsgcache=yes&ctype=text%2Fcss&smaxage=2678400&action=raw& maxage=2678400" type="text/css" media="all" /> <link rel="stylesheet" href="/w/index.php?title=-&action=raw& maxage=2678400&gen=css" type="text/css" media="all" /> <script type="text/javascript"> var skin="monobook", stylepath="http://bits.wikimedia.org/skins-1.5", wgUrlProtocols="http\\:\\/\\/|https\\:\\/\\/|ftp\\:\\/\\/|irc\\:\\/\\/|gopher\\:\\/\\/ |telnet\\:\\/\\/|nntp\\:\\/\\/|worldwind\\:\\/\\/|mailto\\:|news\\:|svn\\:\\/\\/", wgArticlePath="/wiki/$1", wgScriptPath="/w", wgScriptExtension=".php", wgScript="/w/index.php", wgVariantArticlePath=false, wgActionPaths={}, wgServer="http://ja.wikipedia.org", wgCanonicalNamespace="", wgCanonicalSpecialPageName=false, wgNamespaceNumber=0, wgPageName="カーネル", wgTitle="カーネル", wgAction="view", wgArticleId=1178, wgIsArticle=true, wgUserName=null, wgUserGroups=null, wgUserLanguage="ja", wgContentLanguage="ja", wgBreakFrames=false, wgCurRevisionId=31649697, wgVersion="1.16wmf4", wgEnableAPI=true, wgEnableWriteAPI=true, wgSeparatorTransformTable=["", ""], wgDigitTransformTable=["", ""], wgMainPageTitle="メインページ", wgFormattedNamespaces={"-2": "メディア", "-1": "特別", "0": "", "1": "ノート", "2": "利用者", "3": "利用者‐会話", "4": "Wikipedia", "5": "Wikipedia‐ノート", "6": "ファイル", "7": "ファイル‐ノート", "8": "MediaWiki", "9": "MediaWiki‐ノート", "10": "Template", "11": "Template‐ノート", "12": "Help", "13": "Help‐ノート", "14": "Category", "15": "Category‐ノート", "100": "Portal", "101": "Portal‐ノート"}, wgNamespaceIds={"メディア": -2, "特別": -1, "": 0, "ノート": 1, "利用者": 2, "利用者‐会話": 3, "wikipedia": 4, "wikipedia‐ノート": 5, "ファイル": 6, "ファイル‐ノート": 7, "mediawiki": 8, "mediawiki‐ノート": 9, "template": 10, "template‐ノート": 11, "help": 12, "help‐ノート": 13, "category": 14, "category‐ノート": 15, "portal": 100, "portal‐ノート": 101, "画像": 6, "画像‐ノート": 7, "image": 6, "image_talk": 7}, wgSiteName="Wikipedia", wgCategories=["OSのカーネル", "オペレーティングシステムの仕組み"], wgMWSuggestTemplate="http://ja.wikipedia.org/w/api.php?action=opensearch\x26search={searchTerms}\x26namespace={namespaces}\x26suggest", wgDBname="jawiki", wgSearchNamespaces=[0], wgMWSuggestMessages=["検索候補を表示", "検索候補を表示しない"], wgRestrictionEdit=[], wgRestrictionMove=[], wgTrackingToken="16aaac81c3b4e523d135e7527438d348", wgClickTrackingIsThrottled=true, wgNotice="", wgNoticeLocal=""; </script><script src="http://bits.wikimedia.org/skins-1.5/common/wikibits.js?276z56" type="text/javascript"></script> <script src="http://bits.wikimedia.org/skins-1.5/common/ajax.js?276z56" type="text/javascript"></script> <script src="http://bits.wikimedia.org/skins-1.5/common/mwsuggest.js?276z56" type="text/javascript"></script> <script type="text/javascript" src="http://upload.wikimedia.org/centralnotice /wikipedia/ja/centralnotice.js?276z56"></script> <script src="/w/index.php?title=-&action=raw&gen=js& useskin=monobook&276z56" type="text/javascript"></script> </head> <body class="mediawiki ltr ns-0 ns-subject page-カーネル skin-monobook"> <div id="globalWrapper"> <div id="column-content"><div id="content"> <a id="top"></a> <div id="siteNotice"><script type='text/javascript'>if (wgNotice != '') document.writeln(wgNotice);</script><script type="text/javascript" language="JavaScript"> /* <![CDATA[ */ document.writeln("\x3cp\x3e\x3c/p\x3e\n"); /* ]]> */ </script></div> <h1 id="firstHeading" class="firstHeading">カーネル</h1> <div id="bodyContent"> <h3 id="siteSub">出典: フリー百科事典『ウィキペディア(Wikipedia)』</h3> <div id="contentSub"></div> <div id="jump-to-nav">移動: <a href="#column-one">ナビゲーション</a>, <a href="#searchInput">検索</a></div> <!-- start content --> <div class="dablink noprint"> <table style="width:100%; background:transparent;"> <tr> <td style="width:25px;"><a href="/wiki/%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB: Disambig_gray.svg" class="image" title="曖昧さ回避"><img alt="曖昧さ回避" src="http://upload.wikimedia.org/wikipedia/commons/thumb/5/5f/Disambig_gray.svg /25px-Disambig_gray.svg.png" width="25" height="19" /></a></td> <td>この項目では、コンピュータ用語のカーネルについて記述しています。その他の用 法については「<a href="/wiki/%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%AB_(%E6%9B%96 %E6%98%A7%E3%81%95%E5%9B%9E%E9%81%BF)" title="カーネル (曖昧さ回避)">カーネル (曖昧さ回避)</a>」をご覧ください。</td> </tr> </table> </div> <p><b>カーネル</b>(<a href="/wiki/%E8%8B%B1%E8%AA%9E" title="英語">英</a>: <span lang="en" xml:lang="en">Kernel</span>)は、階層型に設計された<a href="/wiki/%E3%82%AA%E3%83%9A%E3%83%AC%E3%83%BC%E3%83%86%E3%82%A3%E3%83%B3%E3 %82%B0%E3%82%B7%E3%82%B9%E3%83%86%E3%83%A0" title="オペレーティングシステム">オ ペレーティングシステム</a> (OS) の中核となる部分である。システムの<a href="/wiki/%E8%A8%88%E7%AE%97%E8%B3%87%E6%BA%90" title="計算資源">リソース</a> を管理し、<a href="/wiki/%E3%83%8F%E3%83%BC%E3%83%89%E3%82%A6%E3%82%A7%E3 %82%A2" title="ハードウェア">ハードウェア</a>と<a href="/wiki/%E3%82%BD%E3 %83%95%E3%83%88%E3%82%A6%E3%82%A7%E3%82%A2" title="ソフトウェア">ソフトウェア </a>コンポーネントのやりとりを管理する。</p> <p>オペレーティングシステムの基本コンポーネントとして、カーネルは<a href="/wiki /Random_Access_Memory" title="Random Access Memory">メモリ</a>、<a href="/wiki/CPU" title="CPU">CPU</a>、<a href="/wiki/%E5%85%A5%E5%87%BA %E5%8A%9B" title="入出力">入出力</a>を中心としたハードウェアを抽象化し、ハード ウェアとソフトウェアがやり取りできるようにする。また、ユーザープログラムのため の機能として、プロセスの抽象化、<a href="/wiki/%E3%83%97%E3%83%AD%E3%82%BB%E3 %82%B9%E9%96%93%E9%80%9A%E4%BF%A1" title="プロセス間通信">プロセス間通信 </a>、<a href="/wiki/%E3%82%B7%E3%82%B9%E3%83%86%E3%83%A0%E3%82%B3%E3%83%BC %E3%83%AB" title="システムコール">システムコール</a>などを提供する。</p> <p>これらのタスクはカーネルによって方式が異なり、設計も<a href="/wiki/%E5%AE %9F%E8%A3%85" title="実装">実装</a>も異なる。<a href="/wiki/%E3%83%A2%E3%83%8E %E3%83%AA%E3%82%B7%E3%83%83%E3%82%AF%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%AB" title="モノリシックカーネル">モノリシックカーネル</a>は全てを一つの仮想アドレス 空間に格納されたコードで実行して性能を向上させようとする。<a href="/wiki/%E3%83 %9E%E3%82%A4%E3%82%AF%E3%83%AD%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%AB" title="マイ クロカーネル">マイクロカーネル</a>はサービスの大部分を<a href="/wiki/%E3%82 %A2%E3%83%89%E3%83%AC%E3%82%B9%E7%A9%BA%E9 %96%93#.E3.83.A6.E3.83.BC.E3.82.B6.E7.A9.BA.E9.96.93" title="アドレス空間">ユー ザー空間</a>で実行し、コードの保守性と<a href="/wiki/%E3%83%A2%E3%82%B8%E3%83 %A5%E3%83%BC%E3%83%AB%E6%80%A7" title="モジュール性" class="mw-redirect">モ ジュール性</a>を向上させようとする<sup id="cite_ref-mono-micro_0-0" class="reference"><a href="#cite_note-mono-micro-0">[1]</a></sup>。多くのカーネ ルはこの二つのカテゴリのいずれか、あるいは中間である。</ <<中略>> <ul id="f-list"> <li id="lastmod"> 最終更新 2010年4月18日 (日) 07:54 (日時は<a href="/wiki/%E7%89%B9%E5%88%A5:%E5%80%8B%E4%BA%BA%E8%A8%AD%E5%AE%9A" title="特 別:個人設定">個人設定</a>で未設定ならば<a href="/wiki/%E5%8D%94%E5%AE%9A%E4%B8 %96%E7%95%8C%E6%99%82" title="協定世界時">UTC</a>)。<br /></li> <li id="copyright">テキストは<a href="http://ja.wikipedia.org /wiki/Wikipedia:Text_of_Creative_Commons_Attribution- ShareAlike_3.0_Unported_License">クリエイティブ・コモンズ 表示-継承ライセンス </a>の下で利用可能です。追加の条件が適用される場合があります。詳細は<a href="http://wikimediafoundation.org/wiki/%E5%88%A9%E7%94%A8%E8%A6%8F%E7%B4 %84">利用規約</a>を参照してください。<br /></li> <li id="privacy"><a href="http://wikimediafoundation.org/wiki/ %E3%83%97%E3%83%A9%E3%82%A4%E3%83%90%E3%82%B7%E3%83%BC%E3%83%BB%E3%83%9D%E3%83 %AA%E3%82%B7%E3%83%BC" title="wikimedia:プライバシー・ポリシー">プライバシー・ ポリシー</a></li> <li id="about"><a href="/wiki/Wikipedia:%E3%82%A6%E3%82%A3 %E3%82%AD%E3%83%9A%E3%83%87%E3%82%A3%E3%82%A2%E3%81%AB%E3%81%A4%E3%81%84 %E3%81%A6" title="Wikipedia:ウィキペディアについて">ウィキペディアについて</a>< </li> <li id="disclaimer"><a href="/wiki/Wikipedia:%E5%85%8D%E8%B2%AC %E4%BA%8B%E9%A0%85" title="Wikipedia:免責事項">免責事項</a></li> </ul> </div> </div> <script type="text/javascript">if (window.runOnloadHook) runOnloadHook(); </script> <!-- Served by srv237 in 0.051 secs. --></body></html>
ということになるが、これも欲しいところを見つけるのは難しい(面倒)だろう。それよりは、XMLで獲得する方法を探してみたい。
と思って、探した結果、
Web検索のカスタマイズを使ったアプリケーションを考える。
Googleは、その昔(2007年頃?)XMLで結果を返すようなサービスをtrialとして提供したが、やめてしまった。基本的にウェブページへ組み込むような(つまり戻された結果を解読しないような)形しか認めていない。
更に調べたところ、大手ネット検索サービスの中で、MSのBingは、XMLで結果を返すサービスを提供している。
http://api.search.live.net/xml.aspx?Appid=<AppID>&sources=image&query=sushiとするといいらしい。以下にマニュアルに載っているいくつかの例
http://api.search.live.net/xml.aspx?Appid=<AppID>&query=sushi&sources=web http://api.search.live.net/xml.aspx?Appid=<AppID>&query=sushi&sources=image http://api.search.live.net/xml.aspx?Appid=<AppID>&query=sushi&sources=news http://api.search.live.net/xml.aspx?Appid=<AppID>&sources=instantanswer&query=what is sushi http://api.search.live.net/xml.aspx?Appid=<AppID>&sources=instantanswer&query=convert 5 feet to meters http://api.search.live.net/xml.aspx?Appid=<AppID>&sources=instantanswer&query= x*5=7 http://api.search.live.net/xml.aspx?Appid=<AppID>&sources=instantanswer&query=2 plus 2 http://api.search.live.net/xml.aspx?Appid=<AppID>&sources=spell&query=cofee http://api.search.live.net/xml.aspx?Appid=<AppID>&sources=phonebook&query=sushi in los angeles http://api.search.live.net/xml.aspx?Appid=<AppID>&sources=relatedqueries&query=sushiAppidはあらかじめBingのサイト http://www.bing.com/developers/createapp.aspx で作っておく必要あり。
<?xml version="1.0" encoding="utf-8" ?> <?pageview_candidate ?> - <SearchResponse xmlns="http://schemas.microsoft.com/LiveSearch/2008/04/XML/element" Version="2.2"> - <Query> <SearchTerms>東邦大学</SearchTerms> </Query> - <web:Web xmlns:web="http://schemas.microsoft.com/LiveSearch/2008/04/XML/web"> <web:Total>115000</web:Total> <web:Offset>0</web:Offset> - <web:Results> - <web:WebResult> <web:Title>学校法人東邦大学</web:Title> <web:Description> 大田区。学部紹介、入試情報、関連学校の紹介。 ... 学校法人東邦大学のホームページ。大学案内、学部・学科、大学院、入試情報、 研究情報、キャンパスライフ、卒業後の進路等。 ... 最新ニュース 2010/04/21 【理学部】 2010年度教員免許更新講習プログラムを公開しました </web:Description> <web:Url>http://www.toho-u.ac.jp/</web:Url> <web:CacheUrl>http://cc.bingj.com/cache.aspx?q=%e6%9d%b1%e9%82%a6%e5%a4%a7%e5%ad%a6&d=4712128967870641&w=8793ac8f,75a0f5c2</web:CacheUrl> <web:DisplayUrl>www.toho-u.ac.jp</web:DisplayUrl> <web:DateTime>2010-05-04T13:59:23Z</web:DateTime> </web:WebResult> - <web:WebResult> <web:Title>東邦大学薬学部</web:Title> <web:Description> 千葉県船橋市。研究室紹介、カリキュラム、入試情報、イベント案内。 ... 学校法人東邦大学薬学部のホームページです。教育内容、研究室、入試情報、大学院、 カリキュラム、イベント、資格、研究施設、卒業後の進路、Q&A,、アクセスマップ、等。 〒274-8510 千葉県船橋市 ... . -2-1 TEL:047(472)0666 当サイトでは ... </web:Description> <web:Url>http://www.phar.toho-u.ac.jp/</web:Url> <web:CacheUrl>http://cc.bingj.com/cache.aspx?q=%e6%9d%b1%e9%82%a6%e5%a4%a7%e5%ad%a6&d=4622553131582745&w=b8de7713,cc53ffa</web:CacheUrl> <web:DisplayUrl>www.phar.toho-u.ac.jp</web:DisplayUrl> <web:DateTime>2010-05-04T03:07:58Z</web:DateTime> </web:WebResult> </web:Results> </web:Web> </SearchResponse>
http://api.search.live.net/xml.aspx?Appid=<AppID>&sources=web&query=OS%20%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%ABとすると、次のような結果が得られた。
<SearchResponse Version="2.2"> <Query> <SearchTerms>OS カーネル</SearchTerms> </Query> <web:Web> <web:Total>1110000</web:Total> <web:Offset>0</web:Offset> <web:Results> <web:WebResult> <web:Title>カーネル - Wikipedia</web:Title> <web:Description> カーネル ( 英: Kernel )は、階層型に設計された オペレーティングシステム (OS) の中核となる部分である。システムの リソース を管理し、 ハードウェア と ソフトウェア コンポーネントのやりとりを管理する。 </web:Description> <web:Url> http://ja.wikipedia.org/wiki/%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%AB </web:Url> <web:CacheUrl> http://cc.bingj.com/cache.aspx?q=os+%e3%82%ab%e3%83%bc%e3%83%8d%e3%83%ab& d=4762556180400182&w=6f3920e1,7ba56074 </web:CacheUrl> <web:DisplayUrl>ja.wikipedia.org/wiki/カーネル</web:DisplayUrl> </web:WebResult> <web:WebResult> <web:Title>Category:OSのカーネル - Wikipedia</web:Title> <web:Description> 出典: フリー百科事典『ウィキペディア(Wikipedia)』 移動: ナビゲーション, 検索 オペレーティングシステム の カーネル に関する項目。 カテゴリ “OSカーネル” にあるページ 以下にこのカテゴリへ属しているページ 15 件中 15 件を表示しています。 </web:Description> <web:Url> http://ja.wikipedia.org/wiki/Category:OS%E3%81%AE%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%AB </web:Url> <web:CacheUrl> http://cc.bingj.com/cache.aspx?q=os+%e3%82%ab%e3%83%bc%e3%83%8d%e3%83%ab& d=5047291034010720&w=47020653,43b7cad7 </web:CacheUrl> <web:DisplayUrl>ja.wikipedia.org/wiki/Category:OSのカーネル</web:DisplayUrl> <web:DateTime>2010-03-22T09:28:15Z</web:DateTime> </web:WebResult> <web:WebResult> <web:Title>カーネルとは 【kernel】 - 意味/解説/説明/定義 : IT用語辞典</web:Title> <web:Description> カーネルとは:OSの基本機能を実装したソフトウェア。OSの中核部分として、 アプリケーションソフトや周辺機器の監視、ディスクやメモリなどの資源の管理、 割りこみ処理、プロセス間通信など、OSとしての基本機能を提供する。追加機能や周辺機器の制御ソフト ... </web:Description> <web:Url>http://e-words.jp/w/E382ABE383BCE3838DE383AB.html</web:Url> <web:DisplayUrl>e-words.jp/w/E382ABE383BCE3838DE383AB.html</web:DisplayUrl> <web:DateTime>2010-05-04T00:09:01Z</web:DateTime> </web:WebResult> </web:Results> </web:Web> </SearchResponse>
# -*- coding: utf-8; -*- import urllib print urllib.quote('いろはにほへと') print urllib.quote(u'いろはにほへと'.encode('euc-jp')) print urllib.quote(u'いろはにほへと'.encode('shift_jis')) print urllib.quote(u'いろはにほへと'.encode('iso-2022-jp')) print urllib.quote(u'いろはにほへと') print urllib.unquote('%E3%81%84%E3%82%8D%E3%81%AF%E3%81%AB%E3%81%BB%E3%81%B8%E3%81%A8')安全を見て、urllib.quote($input_string.encode('utf-8')) ぐらいにするか?
実際に作ったプログラムは、
% cat test-access.py #!/usr/bin/env python # coding: utf-8 import sys import glob import codecs import urllib sys.stdout = codecs.getwriter('utf_8')(sys.stdout) # Command Line Args argvs = sys.argv argc = len(argvs) if (argc != 2): print 'Usage: python %s search_string ' % argvs[0] quit() searchstr = urllib.quote(argvs[1].encode('utf-8')) AppID = '086A186124A3760DD3FB5B64E5CDBD16BC7E129C' url = 'http://api.search.live.net/xml.aspx?Appid=' + AppID + '&sources=web& query=' + searchstr filehandle = urllib.urlopen(url) result = filehandle.read() print result
実行結果は (本当は改行等はないのだが読みづらいので適宜改行した)
% python test-access.py 'OS カーネル' <?xml version="1.0" encoding="utf-8" ?> <?pageview_candidate?> <SearchResponse xmlns="http://schemas.microsoft.com/LiveSearch/2008/04/XML/element" Version="2.2"> <Query><SearchTerms>OS カーネル</SearchTerms></Query> <web:Web xmlns:web="http://schemas.microsoft.com/LiveSearch/2008/04/XML/web"> <web:Total>1110000</web:Total> <web:Offset>0</web:Offset> <web:Results> <web:WebResult> <web:Title>カーネル - Wikipedia</web:Title> <web:Description> カーネル ( 英: Kernel )は、階層型に設計された オペレーティングシステム (OS) の 中核となる部分である。システムの リソース を管理し、 ハードウェア と ソフトウェア コンポーネントの やりとりを管理する。 </web:Description> <web:Url>http://ja.wikipedia.org/wiki/%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%AB</web:Url> <web:CacheUrl>http://cc.bingj.com/cache.aspx?q=os+%e3%82%ab%e3%83%bc%e3%83%8d%e3%83%ab& d=4762556180400182&w=6f3920e1,7ba56074 </web:CacheUrl> <web:DisplayUrl>ja.wikipedia.org/wiki/カーネル</web:DisplayUrl> </web:WebResult> <web:WebResult> <web:Title>Category:OSのカーネル - Wikipedia</web:Title> <web:Description> 出典: フリー百科事典『ウィキペディア(Wikipedia)』 移動: ナビゲーション, 検索 オペレーティングシステム の カーネル に関する項目。 カテゴリ “OSのカーネル” にあるページ 以下にこのカテゴリへ属しているページ 15 件中 15 件を表示しています。 </web:Description> <web:Url>http://ja.wikipedia.org/wiki/Category:OS%E3%81%AE%E3%82%AB%E3%83%BC%E3%83%8D%E3%83%AB</web:Url> <web:CacheUrl>http://cc.bingj.com/cache.aspx?q=os+%e3%82%ab%e3%83%bc%e3%83%8d%e3%83%ab& d=5047291034010720&w=47020653,43b7cad7 </web:CacheUrl> <web:DisplayUrl>ja.wikipedia.org/wiki/Category:OSのカーネル</web:DisplayUrl> <web:DateTime>2010-03-22T09:28:15Z</web:DateTime> </web:WebResult> </web:Results> </web:Web> </SearchResponse>
というように、結果が得られる。応答の中に入っている検索結果の数は多分queryの後に何か書けばよいのだろう。