Last active
October 29, 2017 05:21
-
-
Save tamago324/e0bb3e2b92a2a852d01aed82cba17517 to your computer and use it in GitHub Desktop.
Ver.requests セブンイレブンの今週の新商品(関東)を表示するプログラム
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import re | |
import requests | |
''' | |
セブンイレブンの今週の関東の新商品を表示する | |
毎週火曜日に更新される | |
requestsバージョン | |
''' | |
def main(): | |
html = fetch('http://www.sej.co.jp/i/products/thisweek/kanto/?page=1&sort=f&limit=100') | |
products = scrape(html) | |
displayProducts(products) | |
def fetch(url): | |
''' | |
urlのWebページを取得する。 | |
Webページのエンコーディングは Content-Type から取得する。 | |
:return: str型のHTML | |
''' | |
res = requests.get(url) | |
# encodingをutf-8にする | |
res.encoding = 'utf-8' | |
return res.text | |
def scrape(html): | |
''' | |
HTMLから新商品の情報を取得する | |
:return: 新商品一覧(dictのlist) | |
''' | |
products = [] | |
# 名前、詳細のURL、値段、発売予定日、販売地域 | |
# 商品の情報が記述されている箇所を取得する | |
# re.findallで正規表現で一致した箇所のリストを取得できる | |
for productInfo in re.findall(r'<div class="itemName"><strong><a href=".*?</ul>', html, re.DOTALL): | |
# 商品の詳細のURL | |
product = re.search(r'<div class="itemName"><strong><a href="(.*?)">(.*?)</a>', productInfo) | |
url = 'http://www.sej.co.jp' + product.group(1) | |
# 商品名 | |
name = product.group(2) | |
# 値段 | |
price = re.search('<li class="price">(.*?)</li>', productInfo).group(1) | |
# 発売予定日 | |
launch = re.search('<li class="launch">(.*?)以降順次発売</li>', productInfo).group(1) | |
# 販売地域 | |
region = re.search('<li class="region"><em>販売地域</em>(.*?)</li>', productInfo).group(1) | |
products.append({ | |
'name': name, | |
'price': price, | |
'launch': launch, | |
'region': region, | |
'url': url | |
}) | |
return products | |
def displayProducts(products): | |
''' | |
商品情報を表示する | |
''' | |
for product in products: | |
print('-----------------------------') | |
printStr = ( | |
f'商品名 :{product["name"]}\n' | |
f'値段 :{product["price"]}\n' | |
f'発売日 :{product["launch"]}\n' | |
f'販売地域 :{product["region"]}\n' | |
f'詳細URL :{product["url"]}\n' | |
) | |
print(printStr) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment