Created
December 27, 2013 11:38
-
-
Save hamukichi/8145934 to your computer and use it in GitHub Desktop.
2ちゃんねるのken.cgiをPythonで利用する。http://blog.livedoor.jp/hamu_nbr/archives/32035188.html に掲載。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
Convert hostname (or IP address) into the name of prefecture. | |
""" | |
__author__ = "Hamukichi (Nombiri) <Twitter: @hamukichi_nbr>" | |
__version__ = "1.00" | |
__date__ = "September 13, 2013" | |
__licence__ = "MIT License" | |
# Import modules | |
import requests | |
# The default URI of ken.cgi | |
KENURI = "http://ken.2ch.net/ken.cgi" | |
class Ken2ch: | |
def __init__(self, kenuri = KENURI): | |
""" | |
Initialize the class "Ken2ch". | |
[Parameters] | |
kenuri = KENURI | |
The URI of ken.cgi. | |
""" | |
self.kenuri = kenuri | |
def GetPref(self, ip = None, host = None, mode = 1, keitai = None): | |
""" | |
Get the name of prefecture, using ken.cgi. | |
[Parameters] | |
ip = None | |
Specify the IP address. | |
It is recommended that you use "host" instead of "ip". | |
host = None | |
Specify the Hostname. | |
If you specify, the parameter "ip" will be ignored. | |
mode = 1 | |
Specify how to express the result. | |
Please access http://ken.2ch.net/shikibetsu/ | |
for more detailed information. | |
keitai = None | |
Specify keitai ID such as i-mode ID or EZ number. | |
[Return Values] | |
(str or NoneType) | |
The name of prefecture we acquired using ken.cgi. | |
""" | |
self.errormsg = None | |
# The parameter(s) which will be sent to ken.cgi | |
self.params = {} | |
if (host is None) and (not ip is None): | |
self.params["ip"] = ip | |
if not host is None: | |
self.params["host"] = host | |
self.params["mode"] = mode | |
if not keitai is None: | |
self.params["keitai"] = keitai | |
# Access ken.cgi | |
self.req = requests.get(self.kenuri, params = self.params) | |
self.pref = self.req.content.decode(self.req.encoding) | |
self.req.close() | |
return self.pref | |
def main(): | |
""" | |
Function for demonstration. | |
""" | |
print "[Example]" | |
hosts = ["www.city.kyoto.lg.jp", "www.city.osaka.lg.jp", "www.city.kobe.lg.jp"] | |
k = Ken2ch() | |
for h in hosts: | |
print h, " -> ", k.GetPref(host = h) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment