ど文系の中学校英語教員がプログラミング言語Pythonを学んでみた 21日目 の巻

Saturday, 21 March 2020

プログラミングとPython

 こんにちは、まさです。新学期の準備をしています。学校が始まれば、Pythonの勉強時間も減ってくると思われるので、何とか早めにこれを終わらせたいです。ということで、『退屈なことはPythonにやらせよう』の9章を飛ばして、10章飛ばして、先にやりたかった11章Webスクレイビングに行きます。

➤Webスクレイビングとは、プログラミングを使ってWebからコンテンツをダウンロードすること

➤例えば、cotEditor(シンプルなので使っている)で以下のコードを書き、mapIt.pyの名前で保存。

タイトル
1
2
3
4
5
6
import webbrowser, sys, pyperclip
if len (sys.argv) > 1:
 address = ' '.join(sys.argv[1:])
else:
 address = pyperclip.paste()
webbrowser.open('https://www.google.com/maps/place/' + address)
 これをターミナルから、python mapIt.py '墨田区' で開くと、自動で墨田区のグーグルマップのページを開く。

➤requests.get()関数はダウンロードするURLを文字列として受け取る。type()で調べると、responseオブジェクトであることがわかる。res.status_code == requests.codes.okであれば成功。len(res.text)で総文字数がわかり、最後にprint(res.text[:250])で、冒頭250文字だけを表示する。

タイトル
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> import requests
>>> res = requests.get('http://automatetheboringstuff.com/files/rj.txt')
>>> type(res)
<class 'requests.models.Response'>
>>> res.status_code == requests.codes.ok
True
>>> len(res.text)
178978
>>> print(res.text[:250])
The Project Gutenberg EBook of Romeo and Juliet, by William Shakespeare
 
This eBook is for the use of anyone anywhere at no cost and with
almost no restrictions whatsoever.  You may copy it, give it away or
re-use it under the terms of the Projec
➤requests.get()関数を呼び出したら、必ずraise_for_status()を呼び出して、実際にダウンロードされたか確認必要。raise_for_status()メソッドをtry: except文で囲めば、異常終了せずにエラーを処理できる。

タイトル
1
2
3
4
5
6
7
8
>>> import requests
>>> res = requests.get('http://inventwithpython.com/page_that_does_not_exist')
>>> try:
...     res.raise_for_status()
... except Exception as exc:
...     print('問題あり: {}'.format(exc))
...
問題あり: 404 Client Error: Not Found for url: http://inventwithpython.com/page_that_does_not_exist
➤ダウンロードしたファイルをハードドライブに保存する。100キロバイドが適切な大きさなので、100000。


タイトル
1
2
3
4
5
6
7
8
9
10
>>> import requests
>>> res = requests.get('https://automatetheboringstuff.com/files/rj.txt')
>>> res.raise_for_status()
>>> play_file = open('RomeoAndJuliet.txt', 'wb')
>>> for chunk in res.iter_content(100000):
...     play_file.write(chunk)
...
100000
78978
>>> play_file.close()