beautifulsoup4をインストールしよう

[vagrant@localhost python]$ pip3 install beautifulsoup4
Collecting beautifulsoup4
Downloading https://files.pythonhosted.org/packages/fe/62/720094d06cb5a92cd4b3aa3a7c678c0bb157526a95c4025d15316d594c4b/beautifulsoup4-4.6.1-py3-none-any.whl (89kB)
100% |████████████████████████████████| 92kB 180kB/s
Installing collected packages: beautifulsoup4
Successfully installed beautifulsoup4-4.6.1
You are using pip version 8.1.1, however version 18.0 is available.
You should consider upgrading via the ‘pip install –upgrade pip’ command.

ついでにpipもupgradeします。
[vagrant@localhost python]$ pip install –upgrade pip
Collecting pip
Downloading https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.whl (1.3MB)
100% |████████████████████████████████| 1.3MB 346kB/s
Installing collected packages: pip
Found existing installation: pip 8.1.1
Uninstalling pip-8.1.1:
Successfully uninstalled pip-8.1.1
Successfully installed pip-18.0

数年前、初めてpython触った時、beautifulsoupをインストールできなくて、pythonのスクレピングを諦めたことあったな。あの時なんでできなかったんだろう。今だと一瞬でできるな。

郵便番号をコマンドプロンプトから入力

#!/usr/bin/env python3

# ライブラリの取り込み --- (*1)
import sys
import urllib.request as req
import urllib.parse as parse

if len(sys.argv) <= 1:
	print("USAGE: app.py (keyword)")
	sys.exit()
post = sys.argv[1]

API = "https://maps.googleapis.com/maps/api/geocode/json"
query = {
	"address": post,
    "language": "ja",
    "sensor": "false"
}
params = parse.urlencode(query)
url = API + "?" + params
print("url=", url)

with req.urlopen(url) as r:
	b = r.read()
	data = b.decode("utf-8")
	print(data)

ほう!

[vagrant@localhost python]$ python3 app.py 150-6010
url= https://maps.googleapis.com/maps/api/geocode/json?address=150-6010&sensor=false&language=ja
{
"results" : [
{
"address_components" : [
{
"long_name" : "150-6010",
"short_name" : "150-6010",
"types" : [ "postal_code" ]
},
{
"long_name" : "恵比寿",
"short_name" : "恵比寿",
"types" : [ "political", "sublocality", "sublocality_level_2" ]
},
{
"long_name" : "渋谷区",
"short_name" : "渋谷区",
"types" : [ "locality", "political" ]
},
{
"long_name" : "東京都",
"short_name" : "東京都",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "日本",
"short_name" : "JP",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "日本 〒150-6010",
"geometry" : {
"location" : {
"lat" : 35.6423633,
"lng" : 139.7134531
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 35.6437122802915,
"lng" : 139.7148020802915
},
"southwest" : {
"lat" : 35.6410143197085,
"lng" : 139.7121041197085
}
}
},
"place_id" : "ChIJPwj22RWLGGARAf6hDZkG7aQ",
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}

pythonのlibraryの格納場所

そもそも、import urllibとかしているけど、どこにあるの?

.__file__でわかる。

import datetime
import sys
print(datetime.__file__)
print(sys.__file__)

え、隠しファイル.pyenvの下にあるの? マジかよ!!!
[vagrant@localhost python]$ python3 app.py
/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/datetime.py
Traceback (most recent call last):
File “app.py”, line 4, in
print(sys.__file__)
AttributeError: module ‘sys’ has no attribute ‘__file__’

urllibの下にrequest.pyがありますね。なるほど。

request.pyの中身をみてみます。2674行ですね。
なるほど、これはすげーや。

郵便番号から住所を取得

Google Map Apiにパラメーターを送ります。

import urllib.request
import urllib.parse

API = "https://maps.googleapis.com/maps/api/geocode/json"

values = {
	"address": "160-0002",
	"language": "ja",
	"sensor": "false"
}
params = urllib.parse.urlencode(values)

url = API + "?" + params
print("url=", url)

data = urllib.request.urlopen(url).read()
text = data.decode("utf-8")
print(text)

url= https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=160-0002&language=ja
{
“results” : [
{
“address_components” : [
{
“long_name” : “160-0002”,
“short_name” : “160-0002”,
“types” : [ “postal_code” ]
},
{
“long_name” : “四谷坂町”,
“short_name” : “四谷坂町”,
“types” : [ “political”, “sublocality”, “sublocality_level_2” ]
},
{
“long_name” : “新宿区”,
“short_name” : “新宿区”,
“types” : [ “locality”, “political” ]
},
{
“long_name” : “東京都”,
“short_name” : “東京都”,
“types” : [ “administrative_area_level_1”, “political” ]
},
{
“long_name” : “日本”,
“short_name” : “JP”,
“types” : [ “country”, “political” ]
}
],
“formatted_address” : “日本 〒160-0002”,
“geometry” : {
“bounds” : {
“northeast” : {
“lat” : 35.6920455,
“lng” : 139.7292123
},
“southwest” : {
“lat” : 35.6885298,
“lng” : 139.7245306
}
},
“location” : {
“lat” : 35.6907555,
“lng” : 139.7272033
},
“location_type” : “APPROXIMATE”,
“viewport” : {
“northeast” : {
“lat” : 35.6920455,
“lng” : 139.7292123
},
“southwest” : {
“lat” : 35.6885298,
“lng” : 139.7245306
}
}
},
“place_id” : “ChIJoebNl_SMGGAR4LtICJbkh5I”,
“types” : [ “postal_code” ]
}
],
“status” : “OK”
}

ビットコインでいきたい。
bitflyerから取得する。

import urllib.request
import urllib.parse

url = "https://api.bitflyer.jp/v1/getboard"

# values = {
# 	"product_code": "BTC_JPY",
# }
# params = urllib.parse.urlencode(values)

# url = API + "?" + params
# print("url=", url)

data = urllib.request.urlopen(url).read()
text = data.decode("utf-8")
print(text)

Traceback (most recent call last):
File “app.py”, line 14, in
data = urllib.request.urlopen(url).read()
File “/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/urllib/request.py”, line 163, in urlopen
return opener.open(url, data, timeout)
File “/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/urllib/request.py”, line 472, in open
response = meth(req, response)
File “/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/urllib/request.py”, line 582, in http_response
‘http’, request, response, code, msg, hdrs)
File “/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/urllib/request.py”, line 510, in error
return self._call_chain(*args)
File “/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/urllib/request.py”, line 444, in _call_chain
result = func(*args)
File “/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/urllib/request.py”, line 590, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

HTTP Error 403: Forbiddenと出ています。
>特定のアクセス者にページを表示する権限が付与されず、アクセスが拒否されたことを示すもの。また、サイトの制作者側の設計ミスによる障害やサイトが非常に混雑している時、URLが間違っている場合にも表示される事がある。

なに!!!!!!!?

CCさん。大塚さん、顔が広いらしいですね。

url = "https://coincheck.com/api/ticker"

あら、いけますね♪ 403は、後で確認しましょう。
[vagrant@localhost python]$ python3 app.py
{“last”:911398.0,”bid”:911266.0,”ask”:911422.0,”high”:916800.0,”low”:895000.0,”volume”:2483.42296672,”timestamp”:1532828344}

python, pug, sassで温度、降水量、風量・風向き

python3

import urllib.request
from datetime import datetime

time = datetime.strftime(datetime.now(), "%Y%m%d%H")

url1 = "https://www.jma.go.jp/jp/amedas/imgs/temp/000/"+ time +"00-00.png"
savename = "image/temp.png"
urllib.request.urlretrieve(url1, savename)

url2 = "https://www.jma.go.jp/jp/amedas/imgs/rain/000/"+ time +"00-00.png"
savename = "image/rain.png"
urllib.request.urlretrieve(url2, savename)

url3 = "https://www.jma.go.jp/jp/amedas/imgs/wind/000/"+ time +"00-00.png"
savename = "image/wind.png"
urllib.request.urlretrieve(url3, savename)

print("保存しました")

pug

doctype html
html(lang="ja")
	head
		meta(charset="utf-8")
		link(rel='stylesheet', href="css/style.css")
		title アメダス
	body
		h1 アメダス全国
		hr
		section#top
			h2 降水量
			img.image(
				src="/image/rain.png"
			)
		section#top
			h2 気温
			img.image(
				src="/image/temp.png"
			)
		section#top
			h2 風向・風速
			img.image(
				src="/image/wind.png"
			)

sass

body
	margin: 5px
h1, h2
	margin-top: 0px
	margin-bottom: 0px
#top
	width: 320px
	float: left
.image
	width: 300px
	height: 225px

– jsで日時を表示したい
– illustratorでアイコンを作りたい
– crontabを設定したい
– awsに載せたい
– RSSのニュースを取得して表示したい

あれ、pugは変数もたせて、foreachとかできるんだっけ?できれば、繰り返し処理にしたいところ。

スパゲティコード

日付、時間をハイフンなしで取得(2018072817)を

from datetime import datetime
import re

now = datetime.now()
now = str(now)
slice = now[0:13]
time = re.sub("-","", slice)
time = re.sub(" ","", time)
print(time)

これはあかんわw
[vagrant@localhost python]$ python time.py
2018072817

from datetime import datetime
print(datetime.strftime(datetime.now(), "%Y%m%d%H"))

2行になりました。

[vagrant@localhost python]$ python3 time.py
2018072817

import urllib.request
from datetime import datetime

time = datetime.strftime(datetime.now(), "%Y%m%d%H")

url = "https://www.jma.go.jp/jp/amedas/imgs/temp/000/"+ time +"00-00.png"
print(url)

[vagrant@localhost python]$ python3 app.py
https://www.jma.go.jp/jp/amedas/imgs/temp/000/201807281700-00.png
なるほど。
あれ、まてまてまて、17時って、centos、3時間づれてるぞ。

[vagrant@localhost python]$ date
2018年 7月 28日 土曜日 17:59:52 JST

こうなる、と。

import urllib.request
from datetime import datetime

time = datetime.strftime(datetime.now(), "%Y%m%d%H")

url = "https://www.jma.go.jp/jp/amedas/imgs/temp/000/"+ time +"00-00.png"
savename = "image/amedas.png"

urllib.request.urlretrieve(url, savename)
print("保存しました")

あれ?
[vagrant@localhost python]$ strings /etc/localtime
TZif2
TZif2
JST-9

python3 datetime

import datetime
print(datetime.date.today())

[vagrant@localhost python]$ python3 time.py
2018-07-28

ハイフンを失くしたい。

today = datetime.date.today()
print(type(today))

[vagrant@localhost python]$ python time.py

from datetime import datetime
import re

now = datetime.now()
print(str(now))

[vagrant@localhost python]$ python3 time.py
2018-07-28 16:14:29.145644

import datetimeはdatetimeからimport
from datetime import hogeはdatetimeのhogeからimport
from datetime import datetimeだとややこしいね。

python3でアメダス

import urllib.request

url = "https://www.jma.go.jp/jp/amedas/imgs/temp/000/201807281500-00.png"
savename = "image/amedas.png"

urllib.request.urlretrieve(url, savename)
print("保存しました")

201807281500のところは自動で出力したい。

python2とpython3を使えるようにしよう

[vagrant@localhost ~]$ python -V
Python 3.5.2
[vagrant@localhost centos6]$ python
Python 3.5.2 (default, Jul 28 2018, 11:25:01)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>>
[vagrant@localhost centos6]$ python3
Python 3.5.2 (default, Jul 28 2018, 11:25:01)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>>

時間かかった~ 2日くらい

import urllib.request

url = "http://hogehoge/img/hoge.png"
savename = "test.png"

urllib.request.urlretrieve(url, savename)
print("保存しました")

[vagrant@localhost python]$ python3 app.py
保存しました

おおおお、
では、ヤフオクのmacbookを取得します。

import urllib.request

url = "https://wing-auctions.c.yimg.jp/sim?furl=auctions.c.yimg.jp/images.auctions.yahoo.co.jp/image/dr000/auc0407/users/6ba85c7e48fb6a8607eca71d0b7b7d6113140ce8/i-img1100x983-1532495826yzd18p69701.jpg"
savename = "mac.png"

urllib.request.urlretrieve(url, savename)
print("mac book")

[vagrant@localhost python]$ python3 app.py
mac book

OK

うん、ヤフオクだと、商品画像のアルゴリズムがよくわからんな。
img1100x983が画像サイズでしょうね。
6ba85c7e48fb6a8607eca71d0b7b7d6113140ce8
i-img1100x983-1532495826yzd18p69701.jpg

no module named requests

[vagrant@localhost python]$ pip list
Package Version
————– ———
beautifulsoup4 4.6.0
certifi 2018.4.16
chardet 3.0.4
idna 2.7
libxml2-python 2.9.7
pip 18.0
requests 2.19.1
setuptools 38.5.2
urllib3 1.23
wheel 0.30.0
[vagrant@localhost python]$ python app.py
Traceback (most recent call last):
File “app.py”, line 3, in
import urllib3.requests
ImportError: No module named requests

# -*- coding: utf-8 -*-

import urllib3.requests

url = "http://uta.pw/shodou/img/28/214.png"
savename="test.png"

urllib3.requests.urlretrieve(url, savename)
print("保存しました。")

あれ?