「Pythonエンジニア育成推進協会監修 Python実践レシピ(3) - Mae向きなブログ」の続きです。
Chapter 14 インターネット上のデータを扱う
RequestsはPythonでWebスクレイピングを行う際の定番ツール。
>>> import requests
>>> r = requests.get('http://httpbin.org/get')
>>> r
<Response [200]>
>>> r.text
'{\n "args": {}, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate, br", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.27.1", \n "X-Amzn-Trace-Id": "Root=1-6296bdfc-46a5dc44551a4801724bfd6b"\n }, \n "origin": "172.29.0.1, 219.103.2.254", \n "url": "http://httpbin.org/get"\n}\n'
>>> r.url
>>> r.ok
True
>>> r.json()
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.27.1', 'X-Amzn-Trace-Id': 'Root=1-6296bdfc-46a5dc44551a4801724bfd6b'}, 'origin': '172.29.0.1, 219.103.2.254', 'url': 'http://httpbin.org/get'}
Chapter 15 HTML/XMLを扱う
HTMLのclass属性は、Pythonの予約語との衝突を防ぐためclass_='class名'のように末尾に_を指定する。
>>> from bs4 import BeautifulSoup
>>> from urllib import request
>>> soup = BeautifulSoup(request.urlopen('https://www.python.org'))
>>> soup.find_all('h1')
[<h1 class="site-headline">
<a href="/"><img alt="python™" class="python-logo" src="/static/img/python-logo.png"/></a>
</h1>, <h1>Functions Defined</h1>, <h1>Compound Data Types</h1>, <h1>Intuitive Interpretation</h1>, <h1>Quick & Easy to Learn</h1>, <h1>All the Flow You’d Expect</h1>]
>>> soup.find_all('h1', class_='site-headline')
[<h1 class="site-headline">
<a href="/"><img alt="python™" class="python-logo" src="/static/img/python-logo.png"/></a>
</h1>]
>>> soup.find_all('h1', attrs={'class': 'site-headline'})
[<h1 class="site-headline">
<a href="/"><img alt="python™" class="python-logo" src="/static/img/python-logo.png"/></a>
</h1>]
Chapter 16 テスト
doctestを使った方法はシンプルでいいですね。
sample_doctest.py
"""
与えられた引数について、a / b を行う関数です
>>> div(5, 2)
2.5
"""
def div(a, b):
"""
答えは小数で返ってきます
>>> [div(n, 2) for n in range(5)]
[0.0, 0.5, 1.0, 1.5, 2.0]
"""
return a / b
以下、実行結果です。-m doctest -vをつけて実行すると、doctest.testmod()を書いていないコードのdoctestをコマンドラインで実行できる。
% python sample_doctest.py
% python -m doctest -v sample_doctest.py
Trying:
div(5, 2)
Expecting:
2.5
ok
Trying:
[div(n, 2) for n in range(5)]
Expecting:
[0.0, 0.5, 1.0, 1.5, 2.0]
ok
2 items passed all tests:
1 tests in sample_doctest
1 tests in sample_doctest.div
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
