PythonでURLを指定してhtmlなどのファイルをダウンロードするにはurllib.requestを使用しますが,ユーザーエージェントをどのように扱うのかをメモしておきます.Python3.3で検証しています.
まず,以下のスクリプトを見て下さい.
import urllib.request url = "http://www.cman.jp/network/support/go_access.cgi" req = urllib.request.Request(url) response = urllib.request.urlopen(req) charset = response.headers.get_content_charset() if charset==None: charset = "utf-8" print(charset) html = response.read().decode(charset) open("response.html","w").write(html)
これは,http://www.cman.jp/network/support/go_access.cgi にアクセスして,その結果を"response.html"というファイルに書き出すPython スクリプトです.すると以下の結果が返ってきました.(response.htmlの一部を抜粋)
あなたのブラウザ情報 (HTTP\_USER\_AGENT) : Python-urllib/3.3
これだとPythonで機械的にアクセスしているのがサーバーに分かってしまいます.いくつかのサーバーではユーザーエージェントでアクセスを制限しているところがあるので,標準的なブラウザのユーザーエージェントを設定し,アクセスしてみます.
import urllib.request url = "http://www.cman.jp/network/support/go_access.cgi" headers = { "User-Agent" : "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)" } req = urllib.request.Request(url, None, headers) response = urllib.request.urlopen(req) charset = response.headers.get_content_charset() if charset==None: charset = "utf-8" print(charset) html = response.read().decode(charset) open("response.html","w").write(html)
これを実行すると,以下の結果が返ってきました.
あなたのブラウザ情報 (HTTP\_USER\_AGENT) : Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)