LoginSignup
6
7

More than 5 years have passed since last update.

PythonのRequestsライブラリを使って、WebページとJSONファイルを取得してみる

Last updated at Posted at 2017-09-10

概要

O'Reilly Japan の「PythonとJavaScriptではじめるデータビジュアライゼーション」を参考に、勉強をしています。

requestsライブラリを使ったWebデータの取得

Pythonの「Requests」は、PythonでのHTTPでのやりとりを扱いやすくすることができるライブラリです。

事前準備

requestsのインストール

pip install requests

※バージョン2.7.9以前では、SSLの警告が発生することがある。その場合は、新しいSSLライブラリにアップデートすることで解消する。

pip install --upgrade ndg-httpsclient

requestライブラリの使用例

Wikipediaページのダウンロード(HTMLページとインラインJavaScriptの取得)

>>> import requests
>>> response = requests.get("https://ja.wikipedia.org/wiki/Python");
>>> 
>>> #responsepオブジェクトの属性のリストを取得
>>> dir(response)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', '_next', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'is_permanent_redirect', 'is_redirect', 'iter_content', 'iter_lines', 'json', 'links', 'next', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>>
>>> #responseオブジェクトから、HTTPステータスコードを取得
>>> response.status_code
200
>>>
>>> #responseオブジェクトのtextプロパティを取得すると、HTMLページとインラインJavaScriptを取得できる
>>> response.text
'<!DOCTYPE html>\n<html class="client-nojs" lang="ja" dir="ltr">\n<head>\n<meta charset="UTF-8"/>\n<title>Python - Wikipedia</title>\n<script>document.documentElement.className = document.documentElement.className.replace( /(^|\\s)client-nojs(\\s|$)/, "$1client-js$2" );</script>\n<script>(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"Python","wgTitle":"Python","wgCurRevisionId":65321720,"wgRevisionId":65321720,"wgArticleId":993,"wgIsArticle":true,"wgIsRedirect":false,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":["プログラミング言語","オブジェクト指向言語","スクリプト言語","オープンソース","Python"],"wgBreakFrames
...

JSONフォーマットのデータ取得

>>> import requests
>>> response = requests.get("https://www.oreilly.co.jp/books/9784873118086/biblio.json");
>>> 
>>> #JSONデータの取得
>>> data = response.json()
>>> data
{'title': 'PythonとJavaScriptではじめるデータビジュアライゼーション', 'picture_large': 'http://www.oreilly.co.jp/books/images/picture_large978-4-87311-808-6.jpeg', 'picture': 'http://www.oreilly.co.jp/books/images/picture978-4-87311-808-6.gif', 'picture_small': 'http://www.oreilly.co.jp/books/images/picture_small978-4-87311-808-6.gif', 'authors': ['Kyran Dale\u3000著', '嶋田 健志\u3000監訳', '木下 哲也\u3000訳'], 'released': '2017-08-25', 'pages': 500, 'price': 4104, 'ebook_price': 3283, 'original': 'Data Visulalization with Python and JavaScript', 'original_url': 'http://shop.oreilly.com/product/0636920037057.do', 'isbn': '978-4-87311-808-6'}
>>> 
>>> #キー値の取得
>>> data.keys()
dict_keys(['title', 'picture_large', 'picture', 'picture_small', 'authors', 'released', 'pages', 'price', 'ebook_price', 'original', 'original_url', 'isbn'])
>>> 
>>> #タイトルの取得
>>> data["title"]
'PythonとJavaScriptではじめるデータビジュアライゼーション'

参考

PythonとJavaScriptではじめるデータビジュアライゼーション
https://www.oreilly.co.jp/books/9784873118086/

Requests: 人間のためのHTTP
http://requests-docs-ja.readthedocs.io/en/latest/user/quickstart/
 
 
次回はWeb APIからのデータ利用について勉強します。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7