Skip to content

Instantly share code, notes, and snippets.

@kurozumi
Last active October 16, 2015 10:53
Show Gist options
  • Save kurozumi/86142cfdfad0bddffac6 to your computer and use it in GitHub Desktop.
Save kurozumi/86142cfdfad0bddffac6 to your computer and use it in GitHub Desktop.
【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