【Python】Python ~ 基本編 / urllib ~

■ はじめに

Python から API をコールすることになりそうで
その際に使用する urllib についてメモ。

目次

【1】urllib
 1)使用例
 2)AWS Glue のサポート状況
 補足:サードパーティライブラリ「Requests」
【2】API仕様
 1)urllib.request.Request
 2)urllib.request.urlopen
【3】サンプル
 例1:Hello world
 例2:APIをコールする
【4】補足:サードパーティライブラリ「Requests」

【1】urllib

* URLに関するライブラリ

1)使用例

* urllib.requestモジュールによるWebページの取得

https://atmarkit.itmedia.co.jp/ait/articles/1910/15/news018.html

2)AWS Glue のサポート状況

 AWS Glue 2.0 では、
urllib も requests もサポートしている

https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-libraries.html

より抜粋
~~~~~~~~~~~
Python modules already provided in AWS Glue version 2.0

AWS Glue version 2.0 supports the following python modules out of the box:
requests==2.23.0
urllib3==1.25.8
~~~~~~~~~~~

補足:サードパーティライブラリ「Requests」

* 標準ライブラリurllibよりシンプルに書ける
 => 詳細は、以下のサイトを参照のこと

https://note.nkmk.me/python-requests-usage/

インストール

pip install requests

サンプル

import requests

url = 'https://dk521123.hatenablog.com/entry/2020/11/21/000000'
headers = {
  'Content-Type': 'text/html'
}

response = requests.get(url, headers=headers)

print(response)
print(response.status_code)
print(response.text)
print(response.content)

【2】API仕様

https://docs.python.org/ja/3/library/urllib.request.html

1)urllib.request.Request

* Request オブジェクト を生成する

https://docs.python.org/ja/3/library/urllib.request.html#urllib.request.Request

2)urllib.request.urlopen

* 指定したURLにアクセスし、コンテンツを取得する

https://docs.python.org/ja/3/library/urllib.request.html#urllib.request.urlopen

【3】サンプル

例1:Hello world

import urllib.request

url = 'https://dk521123.hatenablog.com/entry/2020/11/21/000000'
with urllib.request.urlopen(url) as response:
  print(response.info())

例2:APIをコールする

import urllib.request
import json

headers = {
  'Content-Type': 'application/json'
}

request = urllib.request.Request(
  'https://randomuser.me/api/',
  None,
  headers,
  method='GET'
)

with urllib.request.urlopen(request) as response:
  response_body = json.load(response)

  print("****************")  
  print(response_body)
  print("****************")
  gender = response_body['results'][0]['gender']
  print(f"gender: {gender}")
  first_name = response_body['results'][0]['name']['first']
  print(f"name(first): {first_name}")
  last_name = response_body['results'][0]['name']['last']
  print(f"name(last): {last_name}")
  country = response_body['results'][0]['location']['country']
  print(f"country: {country}")

参考文献

https://techacademy.jp/magazine/27217
https://cyublog.com/articles/python-ja/urllib-request-sample/

関連記事

Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python 3 エンジニア認定基礎試験 を受けてみて
https://dk521123.hatenablog.com/entry/2020/12/07/175729
Adobe Analytics ~ API編 ~
https://dk521123.hatenablog.com/entry/2022/07/31/000000
Atlassian/Confluence の REST APIPythonでコールする
https://dk521123.hatenablog.com/entry/2023/02/10/195242