VPCとのVPN接続
Amazon S3 and boto3
忘れそうなのでメモついでにAWS CLIとPythonでS3の使い方をまとめる。
S3の設定
- バケット作成
aws s3 mb s3://バケット名
- バケットにコピー
aws s3 sync images s3://バケット名/images/
- バケットデータ削除
aws s3 rm s3://バケット名/ --include 'img*.jpg' --recursive --dryrun でためして aws s3 rm s3://バケット名/ --include 'img*.jpg' --recursive
- バケットのデータ表示
aws s3 ls s3://バケット名/images/
バケットを作るときに以下のNGが出た場合はAWS内で重複しているのでバケット名を替える必要がある
make_bucket failed: s3://imagebucket An error occurred (BucketAlreadyExists) when calling the CreateBucket operation: The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.
「/」のつけ忘れでフォルダ、ファイルが混同するので注意が必要
最後にpythonでimg-catの中身をS3に転送して結果をCSVに出力するプログラムを書いてみた。
import boto3, pathlib s3 = boto3.client('s3') files = pathlib.Path('img-cat/').glob('*.jpg') for file in files: s3.upload_file('img-cat/'+ file.name, 'バケット名', 'img-cat/' + file.name) objs = s3.list_objects_v2(Bucket='バケット名') csv = '{},{}\n'.format('file', 'size') for o in objs.get('Contents'): key = o.get('Key') size = o.get('Size') if key[-4:]=='.jpg': csv += '{},{}\n'.format(key, int(size)) f = open('uplist.csv', 'w') f.write(csv)
python スクレイピング その7
はじめに
今回はScrapyを使用してNPBの種類ごとの歴代最高記録のURLを取得してみた。
準備
Scrapyのインストール
$ pip install scrapy
Scrapyプロジェクトの作成
$ scrapy startproject npb $ cd npb $ tree . ├── npb │ ├── __init__.py │ ├── items.py │ ├── middlewares.py │ ├── pipelines.py │ ├── settings.py │ └── spiders │ └── __init__.py └── scrapy.cfg 2 directories, 7 files
設定は「settings.py」にまとまっている模様。
item.pyに「url = scrapy.Field()」を追加する。
- items.py
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class NpbItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() url = scrapy.Field() pass
# -*- coding: utf-8 -*- import scrapy class NpbSpiderSpider(scrapy.Spider): name = "npb_spider" allowed_domains = ["npb.jp"] start_urls = ["https://npb.jp/bis/history/"] def parse(self, response): for url in response.css('td.allTimeBatBmn a::attr("href")'): yield response.follow(url) for url in response.css('td.allTimePitBmn a::attr("href")'): yield response.follow(url) pass
- 実行方法&結果
$ scrapy crawl npb_spider 2021-05-15 13:53:42 [scrapy.utils.log] INFO: Scrapy 2.5.0 started (bot: npb) 2021-05-15 13:53:42 [scrapy.utils.log] INFO: Versions: lxml 4.6.1.0, libxml2 2.9.10, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 21.2.0, Python 3.8.5 (default, Sep 4 2020, 07:30:14) - [GCC 7.3.0], pyOpenSSL 19.1.0 (OpenSSL 1.1.1h 22 Sep 2020), cryptography 3.1.1, Platform Linux-5.8.0-45-generic-x86_64-with-glibc2.10 2021-05-15 13:53:42 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.epollreactor.EPollReactor 2021-05-15 13:53:42 [scrapy.crawler] INFO: Overridden settings: 〜〜中略〜〜 2021-05-15 13:53:43 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/> (referer: None) 2021-05-15 13:53:45 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/ltb_g.html> (referer: https://npb.jp/bis/history/) 2021-05-15 13:53:46 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/ltp_l.html> (referer: https://npb.jp/bis/history/) 2021-05-15 13:53:48 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/ltp_w.html> (referer: https://npb.jp/bis/history/) 2021-05-15 13:53:49 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/ltp_nbb.html> (referer: https://npb.jp/bis/history/) 2021-05-15 13:53:50 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/ltp_sho.html> (referer: https://npb.jp/bis/history/) 〜〜中略〜〜
- 簡単な解説
下記でscrapyのプロジェクトを作成している。
$ scrapy startproject npb
$ cd npb
ここでclass名に合致したすべてのaタグのhrefを取得している。
打者成績と投手成績があるので2回取得する処理にしている。
class NpbSpiderSpider(scrapy.Spider): name = "npb_spider" allowed_domains = ["npb.jp"] start_urls = ["https://npb.jp/bis/history/"] def parse(self, response): for url in response.css('td.allTimeBatBmn a::attr("href")'): yield response.follow(url) for url in response.css('td.allTimePitBmn a::attr("href")'): yield response.follow(url) pass
まとめ
簡単かつ大規模なスクレイピングの機能が作れそう。
プロジェクト単位で管理できるので、なにかしらの素材集めをプロジェクトとして管理できそう。
python スクレイピング その6
はじめに
今回は巨人の藤田元司監督のWikiページを画像でコピーする処理を作成した。
準備
- sele_headless.py
from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager import time url = 'https://ja.wikipedia.org/wiki/%E8%97%A4%E7%94%B0%E5%85%83%E5%8F%B8' options = Options() options.add_argument('--headless') driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) driver.get(url) width = driver.execute_script("return document.body.scrollWidth") height = driver.execute_script("return document.body.scrollHeight") driver.set_window_size(width, height) time.sleep(3) driver.save_screenshot("screenshot.png") time.sleep(3) driver.quit()
- 実行方法
$ python sele_screenshot.py
- 簡単な解説
下記で現行のChromeバージョンから最適なドライバを選択してくれる。
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
ここがこの処理の肝だと感じる。
スクリプト実行を意図的に行える。
width = driver.execute_script("return document.body.scrollWidth") height = driver.execute_script("return document.body.scrollHeight") driver.set_window_size(width, height)
まとめ
「ChromeDriverManager().install()」はパス名記載しないので、すごくスタイリッシュで格好良い。
execute_script()の応用の幅がありそう。