Gmailで指定のメールの中から件名を指定し取得

Gmailで指定のメールの中から件名を指定し取得


が指定メール
これのうち
【Shufoo!】お気に入り店舗新着チラシお知らせメール
の件名のもののみ取得するようにする

この中の本文の中のURLへアクセスしチラシを取得する


https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc

杏林堂西田町

https://www.shufoo.net/pntweb/shopDetail/197728/?cid=nmail_pc
ユーコープ/袋井田町店

https://www.shufoo.net/pntweb/shopDetail/15782/?cid=nmail_pc
ぴあご袋井

とりあえず件名が
【Shufoo!】お気に入り店舗新着チラシお知らせメール
のものだけを取得する

vim get_mail_subject.py

中身は

import os.path
import base64
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# 認証情報ファイルのパス
CREDENTIALS_FILE = 'path/to/credentials.json'
TOKEN_FILE = 'token.json'

# Gmail APIのスコープ
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def main():
    # トークンファイルが存在する場合は読み込む
    creds = None
    if os.path.exists(TOKEN_FILE):
        creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
    
    # 認証が有効でない場合は新しく認証を行う
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_FILE, SCOPES)
            creds = flow.run_local_server(port=0)
        # トークンを保存する
        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())

    # Gmail APIクライアントを構築
    service = build('gmail', 'v1', credentials=creds)

    # メールを検索
    query = 'subject:"【Shufoo!】お気に入り店舗新着チラシお知らせメール"'
    results = service.users().messages().list(userId='me', q=query).execute()
    messages = results.get('messages', [])

    if not messages:
        print('No messages found.')
    else:
        print(f'Found {len(messages)} messages:')
        for msg in messages:
            msg_id = msg['id']
            msg = service.users().messages().get(userId='me', id=msg_id).execute()
            msg_snippet = msg['snippet']
            print(f'Message snippet: {msg_snippet}')

if __name__ == '__main__':
    main()

そして認証ファイルをコピーする

cp ../mail_auto/credentials.json .
 cp ../mail_auto/token.json .  

実行すると

Found 24 messages:
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、1件の新着チラシが掲載開始されました。 ・ピアゴ袋井店https://www.shufoo.net/pntweb/shopDetail/15782/?cid=nmail_pc ※Shufoo!PCサイトまたは、シュフーチラシアプリ(スマートフォン・タブレット端末用) からログインしてお店の
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、4件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・ユーコープ/袋井田町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、4件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、1件の新着チラシが掲載開始されました。 ・ピアゴ袋井店https://www.shufoo.net/pntweb/shopDetail/15782/?cid=nmail_pc ※Shufoo!PCサイトまたは、シュフーチラシアプリ(スマートフォン・タブレット端末用) からログインしてお店の
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、4件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・ユーコープ/袋井田町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、1件の新着チラシが掲載開始されました。 ・ピアゴ袋井店https://www.shufoo.net/pntweb/shopDetail/15782/?cid=nmail_pc ※Shufoo!PCサイトまたは、シュフーチラシアプリ(スマートフォン・タブレット端末用) からログインしてお店の
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、1件の新着チラシが掲載開始されました。 ・ピアゴ袋井店https://www.shufoo.net/pntweb/shopDetail/15782/?cid=nmail_pc ※Shufoo!PCサイトまたは、シュフーチラシアプリ(スマートフォン・タブレット端末用) からログインしてお店の
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、4件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・ユーコープ/袋井田町店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、3件の新着チラシが掲載開始されました。 ・杏林堂薬局/袋井旭町店https://www.shufoo.net/pntweb/shopDetail/860335/?cid=nmail_pc ・杏林堂薬局/袋井西田店https://www.shufoo.net/pntweb/
Message snippet: こちらのメールは「Shufoo!」でお気に入り登録した店舗の新着チラシ掲載開始をお知らせするメールです。 以下、1件の新着チラシが掲載開始されました。 ・ピアゴ袋井店https://www.shufoo.net/pntweb/shopDetail/15782/?cid=nmail_pc ※Shufoo!PCサイトまたは、シュフーチラシアプリ(スマートフォン・タブレット端末用) からログインしてお店の

というように
Ctrl + c で止めるまで続く

次に
取得したメールの本文の中に
https://www.shufoo.net/pntweb/shopDetail/15782/?cid=nmail_pc
もしくは
https://www.shufoo.net/pntweb/shopDetail/197728/?cid=nmail_pc
または
https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc
を含んでいる場合 safari の selenium でリンクページを開くようにコード変更

vim mail_url,py

import os.path
import base64
import re
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService

# 認証情報ファイルのパス
CREDENTIALS_FILE = 'path/to/credentials.json'
TOKEN_FILE = 'token.json'

# Gmail APIのスコープ
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

# 検索するURLリスト
URL_LIST = [
    'https://www.shufoo.net/pntweb/shopDetail/15782/?cid=nmail_pc',
    'https://www.shufoo.net/pntweb/shopDetail/197728/?cid=nmail_pc',
    'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
]

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)

def main():
    # トークンファイルが存在する場合は読み込む
    creds = None
    if os.path.exists(TOKEN_FILE):
        creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
    
    # 認証が有効でない場合は新しく認証を行う
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_FILE, SCOPES)
            creds = flow.run_local_server(port=0)
        # トークンを保存する
        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())

    # Gmail APIクライアントを構築
    service = build('gmail', 'v1', credentials=creds)

    # メールを検索
    query = 'subject:"【Shufoo!】お気に入り店舗新着チラシお知らせメール"'
    results = service.users().messages().list(userId='me', q=query).execute()
    messages = results.get('messages', [])

    if not messages:
        print('No messages found.')
    else:
        print(f'Found {len(messages)} messages:')
        for msg in messages:
            msg_id = msg['id']
            msg = service.users().messages().get(userId='me', id=msg_id).execute()
            msg_payload = msg.get('payload', {})
            msg_parts = msg_payload.get('parts', [])
            msg_body = ''

            for part in msg_parts:
                if part['mimeType'] == 'text/plain':
                    msg_body = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8')
                    break

            # URLリスト内のURLを含むか確認
            for url in URL_LIST:
                if url in msg_body:
                    print(f'Opening URL: {url}')
                    open_link_in_safari(url)
                    break

if __name__ == '__main__':
    main()

で実行

しかし取得できないので
メールの最新の1件を取得し その中に指定 のURLがあれば seleniumで開くようにする
が何も表示されないのでログを出力するようにコード変更

import os.path
import base64
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from selenium import webdriver
from selenium.webdriver.safari.service import Service as SafariService

# 認証情報ファイルのパス
CREDENTIALS_FILE = 'path/to/credentials.json'
TOKEN_FILE = 'token.json'

# Gmail APIのスコープ
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

# 検索するURLリスト
URL_LIST = [
    'https://www.shufoo.net/pntweb/shopDetail/15782/?cid=nmail_pc',
    'https://www.shufoo.net/pntweb/shopDetail/197728/?cid=nmail_pc',
    'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
]

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)

def get_email_body(parts):
    """メールパーツを再帰的に探索して本文を取得"""
    for part in parts:
        if part['mimeType'] == 'text/plain' or part['mimeType'] == 'text/html':
            try:
                body = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8')
                return body
            except KeyError:
                continue
            except Exception as e:
                print(f'Error decoding part: {e}')
                continue
        elif 'parts' in part:
            body = get_email_body(part['parts'])
            if body:
                return body
    return None

def main():
    # トークンファイルが存在する場合は読み込む
    creds = None
    if os.path.exists(TOKEN_FILE):
        creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
        print("Loaded credentials from token file.")
    
    # 認証が有効でない場合は新しく認証を行う
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
            print("Credentials refreshed.")
        else:
            flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_FILE, SCOPES)
            creds = flow.run_local_server(port=0)
            print("New credentials obtained.")
        # トークンを保存する
        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())
            print("Credentials saved to token file.")

    # Gmail APIクライアントを構築
    service = build('gmail', 'v1', credentials=creds)
    print("Gmail API client built.")

    # メールを検索
    query = 'subject:"【Shufoo!】お気に入り店舗新着チラシお知らせメール"'
    results = service.users().messages().list(userId='me', q=query, maxResults=1).execute()
    messages = results.get('messages', [])

    if not messages:
        print('No messages found.')
    else:
        print(f'Found {len(messages)} message(s).')
        msg_id = messages[0]['id']
        msg = service.users().messages().get(userId='me', id=msg_id).execute()
        print(f'Fetched message with ID: {msg_id}')
        msg_payload = msg.get('payload', {})
        msg_body = get_email_body(msg_payload.get('parts', []))

        if not msg_body:
            print(f'No body found for message ID: {msg_id}')
            return

        print(f'Message ID: {msg_id}')
        print(f'Message Body: {msg_body[:200]}...')  # メール本文の一部を表示

        # URLリスト内のURLを含むか確認
        for url in URL_LIST:
            if url in msg_body:
                print(f'Opening URL: {url}')
                open_link_in_safari(url)
                break

if __name__ == '__main__':
    main()

結果

Gmail API client built.
Found 1 message(s).
Fetched message with ID: 
No body found for message ID: 

となった

とりあえずラベルを shopにして
Shufooメールを自動振り分けする

とりあえずこのメールで最新のものを取得するようにするが
その前にブラウザで開くようにした

メールの本文が取得できない問題を解決するために、メールのペイロード構造をより詳細に確認し、可能なすべてのパートを再帰的にチェックして本文を取得する方法を強化します。また、HTML形式の本文も考慮しコード変更

import os.path
import base64
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from selenium import webdriver
from selenium.webdriver.safari.service import Service as SafariService

# 認証情報ファイルのパス
CREDENTIALS_FILE = 'path/to/credentials.json'
TOKEN_FILE = 'token.json'

# Gmail APIのスコープ
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

# 検索するURLリスト
URL_LIST = [
    'https://www.shufoo.net/pntweb/shopDetail/15782/?cid=nmail_pc',
    'https://www.shufoo.net/pntweb/shopDetail/197728/?cid=nmail_pc',
    'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
]

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)

def get_email_body(parts):
    """メールパーツを再帰的に探索して本文を取得"""
    for part in parts:
        if part['mimeType'] == 'text/plain' or part['mimeType'] == 'text/html':
            try:
                body_data = part['body'].get('data')
                if body_data:
                    body = base64.urlsafe_b64decode(body_data).decode('utf-8')
                    return body
            except Exception as e:
                print(f'Error decoding part: {e}')
        elif 'parts' in part:
            body = get_email_body(part['parts'])
            if body:
                return body
    return None

def main():
    # トークンファイルが存在する場合は読み込む
    creds = None
    if os.path.exists(TOKEN_FILE):
        creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
        print("Loaded credentials from token file.")
    
    # 認証が有効でない場合は新しく認証を行う
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
            print("Credentials refreshed.")
        else:
            flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_FILE, SCOPES)
            creds = flow.run_local_server(port=0)
            print("New credentials obtained.")
        # トークンを保存する
        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())
            print("Credentials saved to token file.")

    # Gmail APIクライアントを構築
    service = build('gmail', 'v1', credentials=creds)
    print("Gmail API client built.")

    # メールを検索
    query = 'subject:"【Shufoo!】お気に入り店舗新着チラシお知らせメール"'
    results = service.users().messages().list(userId='me', q=query, maxResults=1).execute()
    messages = results.get('messages', [])

    if not messages:
        print('No messages found.')
    else:
        print(f'Found {len(messages)} message(s).')
        msg_id = messages[0]['id']
        msg = service.users().messages().get(userId='me', id=msg_id, format='full').execute()
        print(f'Fetched message with ID: {msg_id}')
        msg_payload = msg.get('payload', {})
        msg_body = get_email_body([msg_payload])

        if not msg_body:
            print(f'No body found for message ID: {msg_id}')
            return

        print(f'Message ID: {msg_id}')
        print(f'Message Body: {msg_body[:200]}...')  # メール本文の一部を表示

        # URLリスト内のURLを含むか確認
        for url in URL_LIST:
            if url in msg_body:
                print(f'Opening URL: {url}')
                open_link_in_safari(url)
                break

if __name__ == '__main__':
    main()

これでURLを開くことができた

改良点
1. メールペイロードの完全な再帰的探索: メールペイロード全体を再帰的に探索し、本文データを見つけ出す。
2. デコードエラーハンドリング: デコードエラーが発生した場合にエラーメッセージを出力して継続する。
3. デバッグ情報の追加: 追加のデバッグ出力により、メールの取得プロセスの各ステップが明確になる。

次に
7/30 日替
というような日付のリンクをクリックするようにする

import datetime
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def click_date_element(driver):
    # 今日の日付を取得
    today_str = datetime.datetime.now().strftime("%m/%d")
    # 日付フォーマットの調整
    today_str = today_str.lstrip("0").replace("/", "月") + "日替"

    try:
        # 日付要素を探してクリック
        element = driver.find_element(By.XPATH, f"//*[contains(text(), '{today_str}')]")
        element.click()
        print(f'Clicked on element with text: {today_str}')
        time.sleep(3)  # クリックした後に3秒間待機
    except Exception as e:
        print(f'Error clicking on element: {e}')

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    click_date_element(driver)
    driver.quit()

if __name__ == '__main__':
    main()

としたが

Error clicking on element: Message: ; For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception

となってしまう

このエラーは、指定された要素がページ上に見つからなかったことを示しています。この問題を解決するためには、ページが完全に読み込まれるまで待機する必要があります。また、指定されたXPathが正しいことを確認する必要があります
とのこと

追加の変更点
1. WebDriverWaitを使用して要素が見つかるまで待機:
pythonコードをコピーする

WebDriverWait(driver, 10).until(
2. EC.presence_of_element_located((By.XPATH, f”//*[contains(text(), ‘{today_str}’)]”))
3. )
4. 


5. デバッグ用に要素のリストを表示: 要素が見つからない場合に、ページ上の要素をリストして表示します。
pythonコードをコピーする

elements = driver.find_elements(By.XPATH, “//*”)
6. for elem in elements:
7. print(elem.text)


ということで

import datetime
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def click_date_element(driver):
    # 今日の日付を取得
    today_str = datetime.datetime.now().strftime("%m/%d")
    # 日付フォーマットの調整
    today_str = today_str.lstrip("0").replace("/", "月") + "日替"

    try:
        # 日付要素を探してクリック
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, f"//*[contains(text(), '{today_str}')]"))
        )
        element = driver.find_element(By.XPATH, f"//*[contains(text(), '{today_str}')]")
        element.click()
        print(f'Clicked on element with text: {today_str}')
        time.sleep(3)  # クリックした後に3秒間待機
    except Exception as e:
        print(f'Error clicking on element: {e}')
        # デバッグ用にページ上の要素をリストする
        elements = driver.find_elements(By.XPATH, "//*")
        for elem in elements:
            print(elem.text)

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    click_date_element(driver)
    driver.quit()

if __name__ == '__main__':
    main()

これで取得した結果を

python click_url.py > shop.txt

でみたけど量が多すぎるので
Chatgptでエラーになる

一度 developer tools でサイトの構成を見る

xpathだと

/html/body/div[1]/div[3]/div[1]/div/div[4]/div/div/div/div/div/div/ul

の中にリンクがある

/html/body/div[1]/div[3]/div[1]/div/div[4]/div/div/div/div/div/div/ul/li[2]/a

がそのリンク
しかし表示されない

import datetime
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def click_date_element(driver, xpath):
    try:
        # 日付要素を探してクリック
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, xpath))
        )
        container = driver.find_element(By.XPATH, xpath)
        # コンテナ内のすべてのリンクを取得
        links = container.find_elements(By.TAG_NAME, 'a')
        today_str = datetime.datetime.now().strftime("%m/%d").lstrip("0").replace("/", "月") + "日替"

        for link in links:
            if today_str in link.text:
                link.click()
                print(f'Clicked on link with text: {link.text}')
                time.sleep(3)  # クリックした後に3秒間待機
                return

        print(f'No link found with text: {today_str}')
    except Exception as e:
        print(f'Error clicking on element: {e}')

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    # ここで指定されたXPathを使用
    xpath = '/html/body/div[1]/div[3]/div[1]/div/div[4]/div/div/div/div/div/div/ul'
    click_date_element(driver, xpath)
    driver.quit()

if __name__ == '__main__':
    main()

直接りんくのHTMLを調べる

<a href="//www.shufoo.net/pntweb/shopDetail/860323/86383836863914/" class="sc_custom_link" rel="sd_shop_chirashi_list" title="7/30 日替">
                          <span class="shop_chirashi_list_thumb"><img src="//ipqcache2.shufoo.net/c/2024/07/26/c/3927665654283/index/img/thumb/thumb_m.jpg" alt=""></span>
                          <span class="shop_chirashi_list_title">7/30 日替</span>
                        </a>

日付を指定せず
日替
と書かれたリンクをクリックするようにした

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def click_date_element(driver, base_xpath):
    try:
        # コンテナ内の日付要素を探してクリック
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        links = container.find_elements(By.XPATH, ".//a[contains(@title, '日替')]")

        for link in links:
            if '日替' in link.get_attribute('title'):
                link.click()
                print(f'Clicked on link with title: {link.get_attribute("title")}')
                time.sleep(3)  # クリックした後に3秒間待機
                return

        print('No link found with title containing: 日替')
    except Exception as e:
        print(f'Error clicking on element: {e}')

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    # ここで指定されたXPathを使用
    base_xpath = '/html/body/div[1]/div[3]/div[1]/div/div[4]/div/div/div/div/div/div/ul'
    click_date_element(driver, base_xpath)
    driver.quit()

if __name__ == '__main__':
    main()

これでクリックはできたので
次に画像を取得

Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/button_cover_turn_over.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/button_cover_turn_over.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/button_cover_basic.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/button_cover_basic.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/button_cover_basic.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/button_cover_basic.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/button_cover_basic.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/button_cover_basic.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://ipqcache2.shufoo.net/c/2024/07/24/29355636822862/index/img/0_100_0.jpg
Found image: https://ipqcache2.shufoo.net/c/2024/07/24/29355636822862/index/img/0_100_1.jpg
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png
Found image: https://www.shufoo.net/site/chirashi_viewer_js/images/transparent.png

となるので

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def get_images_from_container(driver, base_xpath):
    try:
        # コンテナ内の画像要素を探す
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        images = container.find_elements(By.TAG_NAME, 'img')
        
        for img in images:
            src = img.get_attribute('src')
            # 特定の条件に基づいて画像をフィルタリング
            if 'index/img' in src:
                print(f'Found image: {src}')
    except Exception as e:
        print(f'Error finding images: {e}')

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    # ここで指定されたXPathを使用
    base_xpath = '/html/body/div[1]/div[3]/div[1]/div/div[2]/div[2]'
    get_images_from_container(driver, base_xpath)
    driver.quit()

if __name__ == '__main__':
    main()

とする

取得された画像の中には多くの透明画像やボタン画像が含まれているようです。特定の条件に基づいて必要な画像をフィルタリングする必要があります。以下のように、特定の条件を追加して必要な画像のみを取得するようにコードを修正

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def get_images_from_container(driver, base_xpath):
    try:
        # コンテナ内の画像要素を探す
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        images = container.find_elements(By.TAG_NAME, 'img')
        
        for img in images:
            src = img.get_attribute('src')
            # 特定の条件に基づいて画像をフィルタリング
            if 'index/img' in src:
                print(f'Found image: {src}')
    except Exception as e:
        print(f'Error finding images: {e}')

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    # ここで指定されたXPathを使用
    base_xpath = '/html/body/div[1]/div[3]/div[1]/div/div[2]/div[2]'
    get_images_from_container(driver, base_xpath)
    driver.quit()

if __name__ == '__main__':
    main()

コードの説明
1. リンクを開く:
pythonコードをコピーする

url = ‘https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc’
2. driver = open_link_in_safari(url)
3. 


4. XPathに基づいてコンテナを探し、画像要素を取得する:
pythonコードをコピーする

base_xpath = ‘/html/body/div[1]/div[3]/div[1]/div/div[2]/div[2]’
5. get_images_from_container(driver, base_xpath)
6. 


7. 画像URLを取得してフィルタリング:
pythonコードをコピーする

for img in images:
8. src = img.get_attribute(‘src’)
9. # 特定の条件に基づいて画像をフィルタリング
10. if ‘index/img’ in src:
11. print(f’Found image: {src}’)
12. 


このスクリプトは、指定されたXPath内の画像要素を取得し、その画像URLに特定の文字列(index/img)が含まれている場合にのみ出力します。これにより、不要な画像を除外し、必要な画像のみを取得することができます。

結果として

Found image: https://ipqcache2.shufoo.net/c/2024/07/24/29355636822862/index/img/0_100_0.jpg Found image: https://ipqcache2.shufoo.net/c/2024/07/24/29355636822862/index/img/0_100_1.jpg

となった

パスの取得はできたので
指定されたURLを開き、指定されたXPathに基づいて画像を取得し、それらの画像をリストとして返します。さらに、必要に応じて画像をダウンロードする

import time
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def get_images_from_container(driver, base_xpath):
    image_urls = []
    try:
        # コンテナ内の画像要素を探す
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        images = container.find_elements(By.TAG_NAME, 'img')
        
        for img in images:
            src = img.get_attribute('src')
            # 特定の条件に基づいて画像をフィルタリング
            if 'index/img' in src:
                image_urls.append(src)
                print(f'Found image: {src}')
    except Exception as e:
        print(f'Error finding images: {e}')
    return image_urls

def download_images(image_urls):
    for i, url in enumerate(image_urls):
        response = requests.get(url)
        if response.status_code == 200:
            with open(f'image_{i}.jpg', 'wb') as file:
                file.write(response.content)
            print(f'Downloaded image_{i}.jpg')
        else:
            print(f'Failed to download {url}')

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    # ここで指定されたXPathを使用
    base_xpath = '/html/body/div[1]/div[3]/div[1]/div/div[2]/div[2]'
    image_urls = get_images_from_container(driver, base_xpath)
    driver.quit()
    
    # 画像をダウンロード
    if image_urls:
        download_images(image_urls)

if __name__ == '__main__':
    main()

コードの説明
1. リンクを開く:
pythonコードをコピーする

url = ‘https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc’
2. driver = open_link_in_safari(url)
3. 


4. XPathに基づいてコンテナを探し、画像要素を取得する:
pythonコードをコピーする

base_xpath = ‘/html/body/div[1]/div[3]/div[1]/div/div[2]/div[2]’
5. image_urls = get_images_from_container(driver, base_xpath)
6. 


7. 画像URLを取得してリストに追加:
pythonコードをコピーする

for img in images:
8. src = img.get_attribute(‘src’)
9. # 特定の条件に基づいて画像をフィルタリング
10. if ‘index/img’ in src:
11. image_urls.append(src)
12. print(f’Found image: {src}’)

13. 画像をダウンロード:
pythonコードをコピーする

def download_images(image_urls):
14. for i, url in enumerate(image_urls):
15. response = requests.get(url)
16. if response.status_code == 200:
17. with open(f’image_{i}.jpg’, ‘wb’) as file:
18. file.write(response.content)
19. print(f’Downloaded image_{i}.jpg’)
20. else:
21. print(f’Failed to download {url}’)

このスクリプトは、指定されたXPath内の画像要素を取得し、それらの画像URLをリストとして返します。その後、リスト内の画像URLを使用して画像をダウンロードします。ダウンロードされた画像はimage_0.jpg, image_1.jpgのように保存されます。

画像は保存できたので

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def click_date_element(driver, base_xpath):
    try:
        # コンテナ内の日付要素を探してクリック
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        links = container.find_elements(By.XPATH, ".//a[contains(@title, '日替')]")

        for link in links:
            if '日替' in link.get_attribute('title'):
                link.click()
                print(f'Clicked on link with title: {link.get_attribute("title")}')
                time.sleep(3)  # クリックした後に3秒間待機
                return

        print('No link found with title containing: 日替')
    except Exception as e:
        print(f'Error clicking on element: {e}')

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    # ここで指定されたXPathを使用
    base_xpath = '/html/body/div[1]/div[3]/div[1]/div/div[4]/div/div/div/div/div/div/ul'
    click_date_element(driver, base_xpath)
    driver.quit()

if __name__ == '__main__':
    main()

の中にこの処理を追加して画像をダウンロードできるようにする

import time
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def click_date_element(driver, base_xpath):
    try:
        # コンテナ内の日付要素を探してクリック
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        links = container.find_elements(By.XPATH, ".//a[contains(@title, '日替')]")

        for link in links:
            if '日替' in link.get_attribute('title'):
                link.click()
                print(f'Clicked on link with title: {link.get_attribute("title")}')
                time.sleep(3)  # クリックした後に3秒間待機
                return

        print('No link found with title containing: 日替')
    except Exception as e:
        print(f'Error clicking on element: {e}')

def get_images_from_container(driver, base_xpath):
    image_urls = []
    try:
        # コンテナ内の画像要素を探す
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        images = container.find_elements(By.TAG_NAME, 'img')
        
        for img in images:
            src = img.get_attribute('src')
            # 特定の条件に基づいて画像をフィルタリング
            if 'index/img' in src:
                image_urls.append(src)
                print(f'Found image: {src}')
    except Exception as e:
        print(f'Error finding images: {e}')
    return image_urls

def download_images(image_urls):
    for i, url in enumerate(image_urls):
        response = requests.get(url)
        if response.status_code == 200:
            with open(f'image_{i}.jpg', 'wb') as file:
                file.write(response.content)
            print(f'Downloaded image_{i}.jpg')
        else:
            print(f'Failed to download {url}')

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    # 特定のリンクをクリックする
    base_xpath_click = '/html/body/div[1]/div[3]/div[1]/div/div[4]/div/div/div/div/div/div/ul'
    click_date_element(driver, base_xpath_click)
    
    # 画像を取得してダウンロードする
    base_xpath_images = '/html/body/div[1]/div[3]/div[1]/div/div[2]/div[2]'
    image_urls = get_images_from_container(driver, base_xpath_images)
    driver.quit()
    
    if image_urls:
        download_images(image_urls)

if __name__ == '__main__':
    main()

コードの説明
1. リンクを開く:
pythonコードをコピーする

driver = open_link_in_safari(url)
2. 


3. 特定のリンクをクリックする:
pythonコードをコピーする

base_xpath_click = ‘/html/body/div[1]/div[3]/div[1]/div/div[4]/div/div/div/div/div/div/ul’
4. click_date_element(driver, base_xpath_click)
5. 


6. 画像を取得してダウンロードする:
pythonコードをコピーする

base_xpath_images = ‘/html/body/div[1]/div[3]/div[1]/div/div[2]/div[2]’
7. image_urls = get_images_from_container(driver, base_xpath_images)
8. driver.quit()
9.
10. if image_urls:
11. download_images(image_urls)
12. 


このスクリプトは、指定されたURLを開き、「日替」という文字列が含まれるリンクをクリックし、その後、画像を取得してダウンロードします。これにより、リンククリックと画像ダウンロードの処理を一貫して行うことができます。

しかし画像が3分割されて見えにくいので統合する

pip install selenium pillow requests

で必要なライブラリをインストール

import time
import requests
from PIL import Image
from io import BytesIO
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def click_date_element(driver, base_xpath):
    try:
        # コンテナ内の日付要素を探してクリック
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        links = container.find_elements(By.XPATH, ".//a[contains(@title, '日替')]")

        for link in links:
            if '日替' in link.get_attribute('title'):
                link.click()
                print(f'Clicked on link with title: {link.get_attribute("title")}')
                time.sleep(3)  # クリックした後に3秒間待機
                return

        print('No link found with title containing: 日替')
    except Exception as e:
        print(f'Error clicking on element: {e}')

def get_images_from_container(driver, base_xpath):
    image_urls = []
    try:
        # コンテナ内の画像要素を探す
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        images = container.find_elements(By.TAG_NAME, 'img')
        
        for img in images:
            src = img.get_attribute('src')
            # 特定の条件に基づいて画像をフィルタリング
            if 'index/img' in src:
                image_urls.append(src)
                print(f'Found image: {src}')
    except Exception as e:
        print(f'Error finding images: {e}')
    return image_urls

def download_images(image_urls):
    images = []
    for i, url in enumerate(image_urls):
        response = requests.get(url)
        if response.status_code == 200:
            image = Image.open(BytesIO(response.content))
            images.append(image)
            print(f'Downloaded image_{i}.jpg')
        else:
            print(f'Failed to download {url}')
    return images

def merge_images(images, output_path):
    widths, heights = zip(*(img.size for img in images))

    total_height = sum(heights)
    max_width = max(widths)

    combined_image = Image.new('RGB', (max_width, total_height))

    y_offset = 0
    for img in images:
        combined_image.paste(img, (0, y_offset))
        y_offset += img.height

    combined_image.save(output_path)
    print(f'Saved combined image as {output_path}')

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    # 特定のリンクをクリックする
    base_xpath_click = '/html/body/div[1]/div[3]/div[1]/div/div[4]/div/div/div/div/div/div/ul'
    click_date_element(driver, base_xpath_click)
    
    # 画像を取得してダウンロードする
    base_xpath_images = '/html/body/div[1]/div[3]/div[1]/div/div[2]/div[2]'
    image_urls = get_images_from_container(driver, base_xpath_images)
    driver.quit()
    
    if image_urls:
        images = download_images(image_urls)
        if images:
            merge_images(images, 'combined_image.jpg')

if __name__ == '__main__':
    main()

1. リンクを開く:
pythonコードをコピーする

driver = open_link_in_safari(url)
2. 


3. 特定のリンクをクリックする:
pythonコードをコピーする

base_xpath_click = ‘/html/body/div[1]/div[3]/div[1]/div/div[4]/div/div/div/div/div/div/ul’
4. click_date_element(driver, base_xpath_click)
5. 


6. 画像を取得してダウンロードする:
pythonコードをコピーする

base_xpath_images = ‘/html/body/div[1]/div[3]/div[1]/div/div[2]/div[2]’
7. image_urls = get_images_from_container(driver, base_xpath_images)
8. 


9. 画像をダウンロード:
pythonコードをコピーする

images = download_images(image_urls)
10. 


11. 画像を結合して保存:
pythonコードをコピーする

if images:
12. merge_images(images, ‘combined_image.jpg’)
13. 


このスクリプトは、指定されたURLを開き、「日替」という文字列が含まれるリンクをクリックし、その後、画像を取得してダウンロードし、それらを1つの画像ファイルに統合します。統合された画像はcombined_image.jpgとして保存

しかし画像がバラバラ

import time
import requests
from PIL import Image
from io import BytesIO
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.safari.service import Service as SafariService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def open_link_in_safari(url):
    # Safariドライバーを使用してブラウザを起動
    service = SafariService()
    driver = webdriver.Safari(service=service)
    driver.get(url)
    time.sleep(3)  # リンクを開いた後に3秒間待機
    return driver

def click_date_element(driver, base_xpath):
    try:
        # コンテナ内の日付要素を探してクリック
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        links = container.find_elements(By.XPATH, ".//a[contains(@title, '日替')]")

        for link in links:
            if '日替' in link.get_attribute('title'):
                link.click()
                print(f'Clicked on link with title: {link.get_attribute("title")}')
                time.sleep(3)  # クリックした後に3秒間待機
                return

        print('No link found with title containing: 日替')
    except Exception as e:
        print(f'Error clicking on element: {e}')

def get_images_from_container(driver, base_xpath):
    image_urls = []
    try:
        # コンテナ内の画像要素を探す
        container = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, base_xpath))
        )
        images = container.find_elements(By.TAG_NAME, 'img')
        
        for img in images:
            src = img.get_attribute('src')
            # 特定の条件に基づいて画像をフィルタリング
            if 'index/img' in src:
                image_urls.append(src)
                print(f'Found image: {src}')
    except Exception as e:
        print(f'Error finding images: {e}')
    return image_urls

def download_images(image_urls):
    images = []
    for i, url in enumerate(image_urls):
        response = requests.get(url)
        if response.status_code == 200:
            image = Image.open(BytesIO(response.content))
            images.append(image)
            print(f'Downloaded image_{i}.jpg')
        else:
            print(f'Failed to download {url}')
    return images

def merge_images(images, output_path):
    widths, heights = zip(*(img.size for img in images))

    total_height = sum(heights)
    max_width = max(widths)

    combined_image = Image.new('RGB', (max_width, total_height))

    y_offset = 0
    for img in images:
        combined_image.paste(img, (0, y_offset))
        y_offset += img.height

    combined_image.save(output_path)
    print(f'Saved combined image as {output_path}')

def main():
    url = 'https://www.shufoo.net/pntweb/shopDetail/860323/?cid=nmail_pc'
    driver = open_link_in_safari(url)
    # 特定のリンクをクリックする
    base_xpath_click = '/html/body/div[1]/div[3]/div[1]/div/div[4]/div/div/div/div/div/div/ul'
    click_date_element(driver, base_xpath_click)
    
    # 画像を取得してダウンロードする
    base_xpath_images = '/html/body/div[1]/div[3]/div[1]/div/div[2]/div[2]'
    image_urls = get_images_from_container(driver, base_xpath_images)
    driver.quit()
    
    if image_urls:
        images = download_images(image_urls)
        if images:
            merge_images(images, '/mnt/data/combined_image_corrected.jpg')

if __name__ == '__main__':
    main()

で位置が合うか実験

結局位置は合わなかったが画像は一枚になった

直接杏林堂のHPで画像を取得しようとしたが
習慣のチラシになるためこの方法はやめた

とりあえずチラシの取得はできたので
次に
Cloud vision APIで文字列として商品情報が取得できるか試す

Google cloud vision API サンプル

Google cloud vision API サンプル

https://nikkie-ftnext.hatenablog.com/entry/ocr-with-google-vision-api-python-first-step
によれば

Vision APIのOCRには2つあり
* TEXT_DETECTION
* DOCUMENT_TEXT_DETECTION
の2つがある

リファレンスは
https://cloud.google.com/vision/docs/ocr?hl=ja#optical_character_recognition_ocr
TEXT_DETECTION
任意の画像からテキストを検出、抽出します。
たとえば、写真に道路名や交通標識が写っていれば、
抽出された文字列全体、個々の単語、それらの境界ボックスが JSON レスポンスに含まれます。

DOCUMENT_TEXT_DETECTION
画像からテキストを抽出しますが、
高密度のテキストやドキュメントに応じてレスポンスが最適化され、
ページ、ブロック、段落、単語、改行の情報が JSON に含まれます

手書き入力の抽出とファイル(PDF / TIFF)からのテキスト抽出については、DOCUMENT_TEXT_DETECTION をご覧ください

とのこと

コードのサンプルについては
https://cloud.google.com/vision/product-search/docs/samples?hl=ja
にある

とりあえずまず動くか試したいので
2023-03-16【GCP/Python】Vision APIのOCR(光学文字認識)でテキスト抽出!
を参考に動かす

ファイル名を

vision_api_test.py

とする

cd aw10s
cd store_adversting_list 
vim vision_api_test.py


まずは
JSONを任意の場所に置いて読み込むらしいが
情報が古い

この時に認証関連のコマンドを使ってない
2024-01-03GoogleのVision APIをPythonから呼び出して、画像内のテキストを検出する

を参考に
とりあえず

from google.cloud import vision

client = vision.ImageAnnotatorClient()

with open("kanji.png", "rb") as fb:
    content = fb.read()

image = vision.Image(content=content)

response = client.document_text_detection(image=image)
texts = response.text_annotations
print(texts[0].description)

のファイルパスを変えて実行してみる

from google.cloud import vision

client = vision.ImageAnnotatorClient()

with open("test.jpg", "rb") as fb:
    content = fb.read()

image = vision.Image(content=content)

response = client.document_text_detection(image=image)
texts = response.text_annotations
print(texts[0].description)

スマホで撮影したチラシの画像でテスト

実行結果が大量になりそうなので

python vision_api_test.py >> result.txt

でテキストファイルに格納する

結果は

Aグループ版 オモテ
コミュニティー
15
魚担当
おすすめ
16
日
握りのセット!
うなぎの太巻、押寿司
では、うなぎ
―んびょうきゅうりそうなぎの
た
いて
今ぎをのせました。
→サイズ
1208195
うなぎ 28
うなぎ
うなぎり
醬
27.
水公園
coop
ユーコープ
いつもの商品を
膀胱! わくわく 日替りセール!!
お求めやすく!!」
7/100
7/110
7/100
14日
お一家族様
合わせて2点限り
14日
乾
麺10
店頭では10%引の価格を表示しています。
加工食品コーナーの商品に限ります。
※一部対象外の商品がございます。
魚
大
冷凍食品 20
●アイスクリームなど一部対象外商品があります。
詳しくは店頭でご確認ください。
例えばこちらの商品も20%引でこの
7/12 (金
7/13 土
毎週水曜日は
牛乳の日
毎週木曜日は
たまごの日
写真は全てイメージです。
毎週金曜日は
パンの日
コーブ牛乳
お一家族様5点限り
お一家族様 たまご
CO-OP コープ牛乳
1点限り
10個入
パスコ 超熟食パン
静岡県産など
金目鯛切身
切 1パック
680
味つき
734分
えだまめ
超
・6枚
8枚
熟
138円)
刺身用かつお
11バッグ ¥429円
宮格率から 398円 なども
真あじ
128
茶豆
税込
xg 138円
89
参考税込 149 円
天候などにより、水揚げのない場合はご容赦ください。
※写真はイメージです
写真は全てイメージです
新潟県などの国内産
ぶなしめじ 128円
(Wバック)
1袋
税込138円
13
土
7/
8%
群馬県などの国内産
わけあり
牛乳 KOO
成分散調整
「コープ牛乳」
¥198
参考税込
税込 213円
商品は店頭でご確認ください。
7/13 0
1000ml
178
参考税込
8% 192
子音 "14
子育て14日
ポイント
5 倍デー
co-op
岩手ひと
岩手ひとめぼれ
国館
洗米
ブルガリア ¥1,680円 1,780円
18% 各
Co-op
・塩味つきえ
・塩味つき茶
【各250g
15
参考税达 17
8%
19100-1
写真は
です
トマト (小箱)
桃(2個)
1パック/
山梨県などの国内産 ¥498円
$398
茶美豚
鹿児島県-
岩手県:
群馬県產
北海道產
100g当り とかち
100g当り
参考同认
8537
8%
番号税込 429 円
co-op
5ke
あらびきポーク
スペ
商品に限りがあるため、品切れの場合はご容赦ください。
●写真は全てイメージです
茶美酥
豚バラ
うすぎり
ポイントカードはお会計時にご提示ください
明治
特別栽培米
20 特別栽培無洗米
岩手ひとめぼれ 岩手ひとめぼれ
5kg
5kg
ポイントカードはお会計時にご提示ください プリマハム
総菜コーナー
11時販売開始
(本
彩り手巻き寿司
入り)
4本入
658円
710円
本 198円 本 本 378 円
参考税込
※税込) 213円 (交雑種) 税込
408円
販売開始
7種の天ぷら
盛り合わせ
1バック
398円
Dead 429
·伊右衛門
烏龍茶
各2L
配合 138 円
税込
8%
サントリー
税込 149 円
"15"16
ほほえみ
ポイント
15 モチー
限り
スモークの
香薰
こうくん
金賞受賞
香あらびき
キッコーマン ポーク体 238円
濃いだし ウインナー 参考税込 257円
めんつゆ
本つゆ
1L
大体228円
参考税込
税込 246円
※写真はイメージです
本つゆ
通常の5倍
90g×2
合わせ味噌
麺づくり
7/10 水 16 火 お野菜
いつも
※写真は全てイメージです。
おトク宣言!
群馬県などの
国内産
レタス
店内のこの
群馬県などの
国内産
きゃべつ
meiji
くちど
ヨーグルト
明治
R
ブルガリア
LB81
税込 1,814 円
税込 1,922 円
¥400g
LBSD プレーン
ヨーグルトの正本
全体 138円
見た目のキレイ
見た目のキレイ
LROT
参考税込
WWB 400M
税込 149 円
通常の
Aroma
ネスレ
Rich
25
Aroma
Rich
25
www
エクセラ
倍
・無糖
サイズ
コースの
甘さひかえめ お一家族様よりどり2点限り
【茶美豚
マルちゃん
NESCAFE
Excell
Freally
NESCAFE 各900ml
100g当り
ライオン
鹿児島県・
体各
¥78円
アロマリッチ
円 ジュリエット 合 378円 茶美豚
岩手県・群馬県産
198
参考税込
各 84 円
・キャサリン
豚ロース生姜焼・
参考税込
8% 各4円 各詰替950ml
税込 各 415円 豚丼用
参考税込。
8%
1 213 円
麺づくり
・鶏ガラ醤油
0円 ・合わせ味噌合 118
・鶏だし塩 [参考税込
0円 各1食
日香 127円
1個
108
参考税込 116円
1個
138
円 国内産
1個
お酒酒などの肴 158円
税込 149円 ブロッコリー 170円
8%
商品に限りがあるため、品切れの場合はご容赦ください。
●商品に併記している「参考税込」は、お支払い金額の目安として表示しています。 消費税は、レジで精算する際にお買い物小計に対してかかります。 ●酒類・日用品・雑貨などは消費税率10%対象です。 ●お酒は20歳未満の方への販売は致しておりません。
ざいません。
減にもつながります。
①Aグループ版 ウラ
COOP ユーコース
毎週
土曜日は子育て5倍デー 毎月5日 15日 15日 読み
シニア・
ほほえみ
ポイント
本 5 倍デー 7/100-160
組合員限定プレゼント!
対象商品を1点お買上げにつき
レジにて表示のポイントを
プレゼント致します。
広告の売り出し期間
ポイント
「プレゼント
※写真はイメージです
写真はイメージです。
広告実施店 よくお確かめの上、ご来店ください。
冷L中華
しょうゆだま
0000
冷中華
・ごまだれ
5
ポイント
プレゼント
CCO-OP 冷し中華
本番 218 円
・しょうゆだれ・ごまだれ 参考税込 235円
各110g×3食
「ラーメン
19
10%
「プレゼント」
COOD ざるラーメン 各¥ 298円
和風しょうゆつゆ
110g×3食
●税込 321 円
群馬県などの
国内産
たま
各
7/100 140
表示価格は
7/100 140
co-op
を味わう!
「とっておき
北海道産小麦使用
釜揚げうどん
400g
2番 160円)
● 172 円
10%
表示しています。
※写真はイメージです。
乾麺 10%
10%を表示しています。
コーナーのります。
品がございます。
本 158 円
きゅうり 1袋 170m
高知県などの
国内産
おくら 1ネット
149
●写真はイメージです
・コス
MENU
7/10 160
暴口
co-op & コスモ
直火燒
カレールーカレールー
**
カレールー
[カレール
中華
・中辛・辛口
•直火燒
よりどり
108278 (20
税込
300円
りんごカレー
各8皿分
かつお
メージです
うなぎ
神奈川食
ALCI
8594-2580
中原
230-463-36-30
並木あおば店
23342-758-2141
あさ9時よる9
ACC
末吉店 ハーモス深谷 片
045-581-0850 045-853-1141
洋光台店 神大寺店 竹
045-833-1537 045-431-3630
AC
セレク
04
ジョン 指定
鹿児島:大隅産
うなぎ蒲焼(長焼)
本 2,380円
白根店長後駅前店
045-954-1254
0466-43-4121
AC
南台店 茅ヶ崎高
1尾1バック
●者税込 2,570円
20-466-44-7750
0467-51-8777 46
ガッツリお肉で
スタミナチャージ!
[●写真は
イメージ
[100g当り
378円
税込 408円
税込298円
mmmm321
うまさのためにしない
強いこだわり
●平から収屋
当日出荷
さん兄
5
100g当り
全 498 円
ニュージーランド
ニュージーランドビーフ
牛リブロースステーキ 537円
●写真は
ニュージー
ニュージーランドビーフ
牛モモかたまり
ポイント
プレゼント
[焼そば
co-a
ACC
南林間店 ハーモス 厚木戸店
046-274-7202 046-257-3335 045-295-6600
AC
秦野曽屋店
0463-75-0357 0463-83-2830
ALG
城北店 千代田店 富士中央店
54-247-1326 054-264-1991 25-45-55-2555
新沢田店 袋井田町店 小豆店
-25-5000 239-43-7020 053-473-553
さんじの店 桜づつみ店
1053-441-8787 BUSS-989-99228
あさ9時30分よる9時
安台店
1045-983-1321
あさ10mよる8時
100g当り
268円
289 円
太麺焼そば
450g×2食
西港倉店
0467-32-5422
as 10 239-30
神記
大谷店
046-235-6432
A218 夏の
235円
8310 239
井田三舞店
044-798-8806
ハーモス
045-912-9955
東严塚駅前店
45-426-921
上今泉店
0046-231-7263
トマカ
●チャージ祭
7月・8月は
10. 20. 30.
税込 537 円
体 498円
アメリカ産
ブラントさんの牛肉
牛バラカルビ焼肉用
KA
御殿場高原
あらびきポーク
190g
138円)
CO-OP
いろいろ使える
味菜卵の
たま 178円 長ねぎ 1袋
国内産品
茨城県などの
198円
価 213 円
● 192 円
慮ください。
コース 高知県産
産直 黄金しょうが
+ 100円
総菜コーナー 11時販売開始
●写真はイメージです
バック
みょうが(2本): 138円 良) 138円
*税込108円
愛知県の国内産
大業
100g当り
●前
149円
なまぶし
ご飯(いくら)
1袋
があるため、品切れの場合はご容赦ください。
149円
1本釣り刺身用
日光丸で握った 258円
●
使わず
かつおたたき(解凍) 278円
イメージです
冷し中華
COOP
コーコース
7月24号
土用丑の日
3個入
7/130-140
●写真はイコージです
※写真はイメージです。
本
イパック 478 円
24 16
【ご予約承~ 6月15日(土)~7月15日
7月2日月・2日・2日
焼(長焼)
<130g
2380円
2,570 円
本日より1
2.580
しじみ汁に!
EAGEDO
7318
やきとりセット
(もも&ねぎま・たれ)
●516円
バック
4 498 円
537円
入り
ごちそう握り寿司
バック
1,080 円
1,166円
コープ
純正
ごま油
3008
548円
税込591円
イオシッコ
カ
カスピ海
ヨーグルト
グレ 400g
生乳
税込258円
・まさ 278円
82
沖縄県伊平屋島産
味付けもずく
(EHB-REBAV)
70g×3 1バック
コース
178円 税
192
オレ達のえだ豆
4 298円
組合員さんの声
「ほどよいごたえと、
かみしめるほどあふれてくる
ピリカちゃんさん
321がないです!
めください。
ユーコープはいつでもどなたでも加入して、ご利用いただける組合員のお店です。 ホームページはこちらから ユーコープwww.ucoop.or.jp/service/omise ●店舗により一部が異なる場合がございます。万一売り切れの場合はご容敬ください。一部パッケージの
собр
西部エリア

というようにかなり正確に取得できる
以前OCR関連のライブラリで行ったりchatgptで
チラシの内容を表示しようとした時にはできなかったことができた

ただし、スマホの撮影の場合
チラシ以外のものが入ると
その部分まで文字を認識してしまう

次回はチラシの画像のみで行うことにする

チラシの取得は以前Gmailで特定のメールのみ取得することができたので
Shuhooや特売のメールのみ取得し
リンク先から画像を取得すればできそう

あとは画像と数字の結び付け、もしくは
直接商品と価格を結び付けて取得できればOK