【Python】はてなブックマークにログインしてページを取得する方法です。
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
import urllib | |
import urllib2 | |
import os | |
from cookielib import LWPCookieJar | |
class Hatebu(): | |
def __init__(self): | |
self.cookiefile = "cookies.txt" | |
self.cj = LWPCookieJar() | |
if os.path.exists(self.cookiefile): | |
self.cj.load(self.cookiefile) | |
self.opener = urllib2.build_opener() | |
self.opener.add_handler(urllib2.HTTPCookieProcessor(self.cj)) | |
def __del__(self): | |
self.cj.save(self.cookiefile) | |
def request(self, url, postdata): | |
postdata = urllib.urlencode(postdata) | |
return urllib2.Request(url, postdata) | |
def login(self, postdata): | |
url = "https://www.hatena.ne.jp/login" | |
self.opener.open(self.request(url, postdata)) | |
def read(self, url, postdata=""): | |
response = self.opener.open(self.request(url, postdata)) | |
return response.read() | |
if __name__ == '__main__': | |
hatebu = Hatebu() | |
hatebu.login({ | |
"name": "username", | |
"password": "password" | |
}) | |
url = "http://b.hatena.ne.jp" | |
content = hatebu.read(url) | |
print content |
Pythonの勉強をはじめて一週間経ちましたが、今のところPythonはシンプルで覚えやすく楽しいといった印象です。