Skip to content

Instantly share code, notes, and snippets.

@kurozumi kurozumi/hatebu.py
Last active Oct 16, 2015

Embed
What would you like to do?
【Python】はてなブックマークにログインしてトップページの内容を取得する方法
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.