!pip install requests
!pip install beautifulsoup4
!pip install lxml
import requests
from bs4 import BeautifulSoup
import os
# 商品コードをリスト化
item_code_list = ["swim1700","swim2100","swim2988","swim2988-kinsi","swim4800","swim5700"]
for item_code in item_code_list:
# 商品コードでurlを指定
url = 'https://item.rakuten.co.jp/unimed/' + item_code + '/'
# web取得
response = requests.get(url)
# 成功か判定
print(response)
# url解析
soup = BeautifulSoup(response.content,"html.parser")
# metaタグのitempropに「image」を指定
images = soup.find_all('meta',itemprop ='image')
# スクレイピングした画像(metaタグのcontent属性の値(画像のソース))を一つずつ取り出す。
for target in images:
#各タグのsrcを取得
re = requests.get(target['content'])
# Pythonと同じ階層にある「pictures」フォルダの下に商品コード名で新しいディレクトリを指定
dir = './pictures/'+ item_code + '/' # 作りたいディレクトリ名
os.makedirs(dir, exist_ok=True)
i = 1
for target in images:
re = requests.get(target['content'])
# 取得した画像を同じディレクトリのpicturesフォルダの下層ディレクトリ(商品コード名)を開けて「商品コード_数字」として保存します
with open(str(dir)+item_code+ "_" +str(i)+str('.jpeg'), 'wb')as f:
# 保存します
f.write(re.content)
i += 1
8