HTTP/GETでWebページを取得する
# -*- coding: utf-8 -*-
import urllib.request
if __name__ == '__main__':
page_text = ""
# urlopenはurllib.responseオブジェクトを返す
# urllib.responseはfileのようなオブジェクトで、infoメソッドとgeturlが追加されたもの
with urllib.request.urlopen('http://www.google.co.jp') as page:
# WebページのURLを取得する
print(page.geturl())
# infoメソッドは取得したページのメタデータを返す
print(page.info())
# readlinesでWebページを取得する
for line in page.readlines():
page_text = page_text + line.decode('Shift_JIS')
print(page_text)
2. HTTP/POSTでWebページにデータを送信する
# -*- coding: utf-8 -*-
import urllib.request
if __name__ == '__main__':
# はてなのログインURL
LOGIN_URL = "https://www.hatena.ne.jp/login"
post_data = {
'name': 'ログインID',
'password': 'ログインパスワード',
'persistent': '1',
'location': 'http://b.hatena.ne.jp/?&login_date=1371363089666',
}
# POSTで送信するデータをURLエンコードする
encoded_post_data = urllib.parse.urlencode(post_data).encode(encoding='ascii')
page_text = ""
# urlopenのdata引数を指定するとHTTP/POSTを送信できる
with urllib.request.urlopen(url=LOGIN_URL, data=encoded_post_data) as page:
# WebページのURLを取得する
print(page.geturl())
# infoメソッドは取得したページのメタデータを返す
print(page.info())
# readlinesでWebページを取得する
for line in page.readlines():
page_text = page_text + line.decode('utf-8')
print(page_text)
0 Kommentarer:
コメントを投稿