LoginSignup
0
1

More than 1 year has passed since last update.

fresh撮影会をスクレイピング

Posted at

fresh撮影会の予定をスクレイピングします。
画像保存フォルダimg/fresh/を作成してください。
作成されるCSVは
・リンク、名前、日付、スタジオ、スタジオリンク、SNSリンク、スケジュール、画像
となっています。
CSVの画像はimg/fresh/に保存される画像ファイルの名前になっています。
CSVからHTML変換すると見やすくなります。
(中途半端なやり方で欲しい人がいたら載せます)

fresh.py
from bs4 import BeautifulSoup
import urllib.request
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
import re
import requests
import time
from time import sleep
import datetime
import pandas as pd
from requests_html import HTMLSession
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_binary
from selenium.webdriver.common.keys import Keys

now = datetime.datetime.now()
filename = now.strftime('fresh%Y%m%d_%H%M%S') + '.csv'
f = open(filename,'a', encoding='cp932',errors='ignore')
f.write("リンク,名前,日付,スタジオ,スタジオリンク,SNSリンク,スケジュール,画像")
f.write("\n")

options = Options()
options.add_argument('--headless')
chromedriver = "C:\code\python\chromedriver.exe"
driver = webdriver.Chrome(executable_path=chromedriver,options=options)
########################################################################################
#画像保存
def img_store(path):
    img = requests.get(path).content
#写真なしの場合の画像の名前
    if "noPhoto.gif" in path:
        name=path.partition('photo/')[2]
#写真ありの場合の画像の名前
    else:
        name=path.partition('talent/')[2]
    with open("img/fresh/"+name, "wb") as f:
        f.write(img)
#######################################################################################

##################################################################################
def linklist(url):
#各撮影会のスケジュールのリンクを取得

    soup = BeautifulSoup(url, 'lxml')
#    print(soup)
    linklist=[]

#トップページの撮影会予定リンクを取得
    for a in soup.find_all('a'):
#各リンク先delailのみ取得
        if "/detail/" in a.get("href"):
            linklist.append("https://www.fresh-club.net"+a.get('href'))
            print(a.get('href'))
#各リンクをソート、キーはインデックス
    linklist = sorted(list(set(linklist)),key=linklist.index)
    print(linklist)
    return linklist
##################################################################################

#################################################################################
def akbmodel(linklist):
#フォトセッションのモデルの情報を取得
#linnklistのURLが開けない場合飛ばす
    try:
        urlopen(linklist)
    except URLError as e:
        #エラーの場合の処理
        print("URLに接続するが処理できない")
        return "?"
#URLが開けたときスクレイピング
    else:
        html = urllib.request.urlopen(linklist)
        soup = BeautifulSoup(html, 'lxml')
#        print(linklist)

#フォトセッション共通のテーブルの書き込み
#場所のリンク取得
        rows =  soup.find_all("tr")
        for row in rows:
            for cell in row.findAll('td'):
                try:
                    if "service" in cell.find('a')['href']:
                        print(cell.find('a')['href'])
                    else:
                        studio = ("https://www.fresh-club.net/" + cell.find('a')['href'])
#                        print(studio)
                except:
                    pass
#開催日時・場所・参加方法のテーブル
        dfs = pd.read_html(linklist)[0]
#日時
        data1 = dfs[1][0]
        data2 = (re.split('(|)', data1))
        date = data2[0]
#場所
        prace = dfs[1][1]
#参加料金のテーブル
        dfs = pd.read_html(linklist)[1]
        price =('"'+data2[2]+"\n"+dfs[0][0]+"\n"+dfs[1][0]+"\n"+dfs[0][1]+"\n"+dfs[1][1]+"\n"+dfs[0][2]+"\n"+dfs[1][2]+"\n"+'"')
        print(price)
#フォトセッションの各モデルの情報
        for a in soup.find('div',class_="akbModel").find_all("li",class_="item"):
#リンク
            f.write(linklist)
            f.write(",")
#名前
            name = a.find("p",class_="name").text
            f.write(name)
            f.write(",")
#日付
            f.write(date)
            f.write(",")
#スタジオ
            f.write(prace)
            f.write(",")
#スタジオリンク
            f.write(studio)
            f.write(",")
#sns
            try:
                sns = a.find("a")["href"]
                f.write(sns)
                f.write(",")
            except:
                f.write("none")
                f.write(",")
#料金
            f.write(price)
            f.write(",")
#画像リンク(画像取得用)
            src = a.find("img",class_="main").get("src")
#画像なしの場合の画像リンク
            if "noPhoto.gif" in src:
                src="https://www.fresh-club.net/"+src
            img_store(src)
            if "noPhoto.gif" in src:
                src=src.partition('photo/')[2]
            else:
                src=src.partition('talent/')[2]
            f.write(src)
            f.write("\n")
            print(src)
#人によってクラスtimeがないので
            if a.find("p",class_="time") is None:
                print("none")
            else:
                swimsuit = a.find("p",class_="time").text
#                print(swimsuit)
###########################################################################################

###########################################################################################
def outmodel(linklist):
#屋外撮影のモデルの情報を取得
    try:
        urlopen(linklist)
    except URLError as e:
        #エラーの場合の処理
        print("URLに接続するが処理できない")
        return "?"
    else:
        html = urllib.request.urlopen(linklist)
        soup = BeautifulSoup(html, 'lxml')
        print(linklist)

#モデルのテーブル
        rows =  soup.find_all("tr")
#場所のリンク
        stulink=[]
        for row in rows:
            for cell in row.findAll('td'):
                try:
                    stulink.append(cell.find('a')['href'])
#                    print(sns)
                except:
                    pass
        studio = stulink[0]
#        print(studio)
        dfs = pd.read_html(linklist)[0]
#        print(dfs)
#撮影会名 イベント名
#        print(dfs[1][0])
#日付 開催日
        data1=dfs[1][1]
        data2 = (re.split('(|)', data1))
        date = data2[0]

#場所 開催場所 表の行数が違う場合があるので場合分け
        if "開催場所" in dfs[0][3]:
            prace=dfs[1][3]
        else:
            prace=dfs[1][4]
#料金時間  表の行数が違う場合があるので場合分け
        if "開催場所" in dfs[0][3]:
            price=('"'+dfs[1][2]+"\n"+dfs[1][6]+'"')
        else:
            price=('"'+dfs[1][2]+"\n"+dfs[1][7]+'"')

        if "前売チケットを申し込む" in price:
            price=price.partition('前売チケットを申し込む')[0]
            price=price.replace("[参加費] お得な前売りチケット発売中!数量限定ですのでお早めにご購入下さい!","")
            price=(price+'"')
        elif "チケットを申し込む" in price:
            price=price.partition('チケットを申し込む')[0]
            price=price.replace("[参加費] お得な前売りチケット発売中!数量限定ですのでお早めにご購入下さい!","")
            price=(price+'"')
        else:
            print("aaa")

        for a in soup.find('div',class_="outdoorModel").find_all("li"):
            sns = a.find("a")
            #print(sns)
#liが空の場合があるので、aタグであるかないか判断
            if None == sns:
                print("nanasi")
            else:
#リンク
                f.write(linklist)
                f.write(",")
#名前 
                name=sns.text
                name=re.sub(r"[\n\t\s,]*", "", str(name))
#                print(name)
                f.write(name)
                f.write(",")

#日付
                f.write(date)
                f.write(",")
#スタジオ
                f.write(prace)
                f.write(",")
#スタジオリンク
                f.write(studio)
                f.write(",")
#sns            
                sns = a.find("a")
                try:
#                    print(sns.get("href"))
                    f.write(sns.get("href"))
                    f.write(",")
                except:
                    f.write("none")
                    f.write(",")
#料金
                f.write(price)
                f.write(",")

#画像
                try:
                    src = a.find("img",class_="main").get("src")
                    if "noPhoto.gif" in src:
                        src="https://www.fresh-club.net/"+src
#                   print(src)
                    img_store(src)
                    if "noPhoto.gif" in src:
                        src=src.partition('photo/')[2]
                    else:
                        src=src.partition('talent/')[2]
                    f.write(src)
                    f.write("\n")
                    print(src)
                except:
                    f.write("none")
                    f.write("\n")
                    pass





############################################################################################

###########################################################################################
def premodel(linklist):
#プレミアムセッションのモデルの情報を取得

    try:
        urlopen(linklist)
    except URLError as e:
        #エラーの場合の処理
        print("URLに接続するが処理できない")
        return "?"
    else:
        html = urllib.request.urlopen(linklist)
        soup = BeautifulSoup(html, 'lxml')

        date=soup.find("h2").text
        name=[]
        sns=[]
        studio=[]
        src=[]
        for a in soup.find_all('div',class_="item"):

            for b in a.find_all("div",class_="photo"):
#ツイッター

                 if b.find("a") or not b.find("span"):
                    for c in b.find_all("a"):
                     #   print(c.get("href"))
                        sns.append(c.get("href"))
                 else:
                  #  print("none")
                    sns.append("none")

                 #print(b.find("a"))

#名前
                 for c in b.find_all('img'):
                    if "NEW" != c.get("alt") and "" != c.get("alt"):
                        name.append(c.get("alt"))
#画像 
#画像なしの場合のリンク                   
                    if "noPhoto.gif" in c.get("src"):
                        src.append("https://www.fresh-club.net"+c.get("src"))
#バースデーの画像を飛ばすため
                    elif "common" in c.get("src"):
                        print("")
#NEWの画像を飛ばすため
                    elif "new" in c.get("src"):
                        print("")
                    else:
                        src.append(c.get("src"))

#スタジオリンク
            for b in a.find("table",class_="basicTable").find_all("a"):
                studio.append(b.get("href"))

        i=0                 
        dfs = pd.read_html(linklist)
        #print(dfs)
        for table in dfs:
#リンク
            f.write(linklist)
            f.write(",")
#名前
            f.write(name[i])
            f.write(",")
#日付
            f.write(date)
            f.write(",")

#開催場所
            prace=(table[1][1])
#スタジオ
            f.write(prace)
            f.write(",")
#スタジオリンク
            f.write(studio[i])
            f.write(",")
#sns            
            f.write(sns[i])
            f.write(",")
#参加費
#開催状況
            table[1][0]=table[1][0].replace(" ","")
            table[1][0]=table[1][0].replace("予約済"," 予約済\n")
            table[1][0]=table[1][0].replace("申込受付中"," 申込受付中\n")
            price=('"'+table[1][2]+"\n"+table[1][0]+'"')
#料金
            f.write(price)
            f.write(",")
            print(src[i])
            img_store(src[i])
            if "noPhoto.gif" in src[i]:
                src[i]=src[i].partition('photo/')[2]
            else:
                src[i]=src[i].partition('talent/')[2]
            f.write(src[i])
            f.write("\n")
            print(src[i])
            i+=1


##############################################################################################

##################################################################################################
#日付、撮影会名、場所、名前、時間、予約状況、値段、サイトURL、名前SNS、名前画像

#フォトセッション
driver.get("https://www.fresh-club.net/akb/")
sleep(1)
html = driver.page_source.encode('utf-8')
links=linklist(html)
for link in links:
    akbmodel(link)


#akbmodel("https://www.fresh-club.net/akb/detail/2669")



#屋外
driver.get("https://www.fresh-club.net/outdoor/")
sleep(1)
html = driver.page_source.encode('utf-8')
links=linklist(html)
for link in links:
    outmodel(link)


#outmodel("https://www.fresh-club.net/outdoor/detail/717")

#プレミアム
driver.get("https://www.fresh-club.net/premium/")
sleep(1)
html = driver.page_source.encode('utf-8')
links=linklist(html)
for link in links:
    premodel(link)

#premodel("https://www.fresh-club.net/premium/detail/2252")
"""
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1