omatsushinya
@omatsushinya

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

find_elements(By の書き換えがわかりません

Q&A

Closed

解決したいこと

ホームページ上でエラーが発生した場合
ログイン、ログアウトを繰り返すプログラムなのですが
ログアウト後ログインがされません

発生している問題・エラー

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

例)

with open("result\{}.txt".format(file_name), "a") as f:
087201 ログインに成功
Traceback (most recent call last):
  File "/home/???/anaconda3/bin/2024/年伏見.py", line 217, in <module>
    reservation_facility()
  File "/home/???/anaconda3/bin/2024/年伏見.py", line 211, in reservation_facility
    log_out(driver)
  File "/home/???/anaconda3/bin/2024/年.py", line 62, in log_out
    driver.find_element(By.XPATH,('//*[@id="global-navs-1-drawer"]/div[1]/nav/div[2]/div/div[2]/a[2]')).click()
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/???/anaconda3/lib/python3.12/site-packages/selenium/webdriver/remote/webdriver.py", line 770, in find_element
    return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/???/anaconda3/lib/python3.12/site-packages/selenium/webdriver/remote/webdriver.py", line 384, in execute
    self.error_handler.check_response(response)
  File "/home/???/anaconda3/lib/python3.12/site-packages/selenium/webdriver/remote/errorhandler.py", line 232, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="global-navs-1-drawer"]/div[1]/nav/div[2]/div/div[2]/a[2]"}
  (Session info: chrome=131.0.6778.85); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception
Stacktrace:

または、問題・エラーが起きている画像をここにドラッグアンドドロップ

該当するソースコード

import sys, os
import json
import time
import datetime
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By

class NotFound(Exception):
    pass

def find_xpath(driver, xpath, flag=True):
    time.sleep(2)
    if len(driver.find_elements(By.XPATH,xpath)) != 0:
        return driver.find_elements(By.XPATH,xpath)
    #if len(driver.find_elements(By.XPATH,(xpath))) != 0:
    #return driver.find_elements(By.XPATH,(xpath))
            #driver.find_element_by_id(id).send_keys(name)
            #driver.find_element(By.ID,id).send_keys(name)
    else:
        if flag:
            raise NotFound("要素が見つからない")
        else:
            return []

def find_list_box_click(driver, find_name, index):
    found = 0
    flag = False
    for i in range(index, index + 20):
        for j in range(0, 5):
            found = len(driver.find_elements(By.XPATH,('//*[@id="list-item-{}-{}"]'.format(i, j))))
            if found != 0:
                elements = driver.find_elements(By.XPATH,('//*[@id="list-item-{}-{}"]'.format(i, j)))
                for element in elements:
                    if find_name in element.text:
                        element.click()
                        flag = True
    if flag:
        return True, i
    else:
        return False, i
        
def log_in(driver, id_num, password, sleep_time):
    time.sleep(3)
    driver.find_element(By.XPATH,('//*[@id="main"]/div[1]/div[2]/div[1]/span[1]/a/span/div/span/span')).click()
    driver.find_element(By.ID,"input-21").send_keys("00" + id_num)
    driver.find_element(By.ID,"input-25").send_keys(password)
    while len(driver.find_elements(By.XPATH,('//*[@id="fixed-btn-container-3"]/div[1]/div/button'))) != 0 :
        driver.find_elements(By.XPATH,('//*[@id="fixed-btn-container-3"]/div[1]/div/button'))[0].click()
        time.sleep(sleep_time)

def log_out(driver):
    time.sleep(2)
    driver.find_element(By.XPATH,('//*[@id="app"]/div[2]/header/div/div[2]/button')).click()
    time.sleep(2)
    #if driver.find_element(By.XPATH,('//*[@id="globalConfigDialog-footer"]/div/div[2]/button')):
    #    driver.find_element(By.XPATH,('//*[@id="globalConfigDialog-footer"]/div/div[2]/button'))[0].click()
    #    time.sleep(1)
    #    driver.find_element(By.XPATH,('//*[@id="app"]/div[2]/header/div/div[2]/button[2]'))[0].click()
    #time.sleep(2)
    driver.find_element(By.XPATH,('//*[@id="global-navs-1-drawer"]/div[1]/nav/div[2]/div/div[2]/a[2]')).click()
   #driver.find_element(By.XPATH,('//*[@id="global-navs-1-drawer"]/div[1]/nav/div[2]/div/div[2]/a[2]'))[0].click()

def reserve(driver, id_num, res_dict, password="shinya37"):

    mokuteki = res_dict["mokuteki"]
    #tiku = res_dict["tiku"]
    shisetu = res_dict["shisetu"]
    nitiji = res_dict["nitiji"]

    # ログイン
    ret = find_xpath(driver,'//*[@id="main"]/div[1]/div[2]/h2')
    if len(ret) == 0:
        driver.get('https://yoyaku.harp.lg.jp/sapporo/')
    
    if "ログイン中" not in driver.find_elements(By.XPATH,('//*[@id="main"]/div[1]/div[2]/h2'))[0].text:
        i = 0
        while i < 10:
            i += 1
            try:
                log_in(driver, id_num, password, 2)
                print("{} ログインに成功".format(id_num))
            except:
                print("{} ログインに失敗".format(id_num))
                driver.get('https://yoyaku.harp.lg.jp/sapporo/')
                time.sleep(3)
            else:
                break
        if i >= 10:
            return False, "ログイン失敗"

    #   目的用途検索
    results = list()
    list1 = [mokuteki, shisetu, nitiji]
    id_list = ["input-15", "input-36", "input-48"]
    time.sleep(1)
    index = 210
    try:
        for id, name in zip(id_list, list1):
            driver.find_element(By.ID,id).send_keys(name)
            time.sleep(2)
            ret, index = find_list_box_click(driver, name, index)
            results.append(ret)
            
        driver.find_element(By.XPATH,('//*[@id="search-form-2-formContainer"]/form/div/div[1]/button')).click()
        driver.find_element(By.XPATH,('//*[@id="search-form-2-formContainer"]/form/div/div[1]/button')).click()

        # 登録予約
        time.sleep(2)

                
            elif "該当する施設・室場がありません。""該当する施設・室場がありません。" in i.text:
                return False, "該当施設なし"
            else:
                return False, ""
        return True, ""
    except Exception as e:
        driver.get('https://???/')
        if "ログイン中" in driver.find_elements(By.XPATH,('//*[@id="main"]/div[1]/div[2]/h2'))[0].text:
            
            log_out(driver)
        return False, e
    


def reservation_facility(json_path="/home/???/anaconda3/bin/setting//data.json", id_path="/home/???/anaconda3/bin/setting//id_list.txt"):

    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    driver = webdriver.Chrome()

    with open(id_path, "r") as f:
        id_list = list(f)

    with open(json_path, encoding='UTF-8') as f:
        res_dict = json.load(f)

    id_lists = [i.split("\n")[0] for i in id_list]
    os.makedirs("result", exist_ok = True)
    file_name = datetime.datetime.now().strftime('%Y%m%d%H%M')

    with open("result\{}.txt".format(file_name), "a") as f:
        driver.get('https://???/')
        for id_num in id_lists:
            for d in res_dict:
                f.write(text)
            log_out(driver)

    driver.quit()
if __name__ == '__main__':
    reservation_facility()

自分で試したこと

ログアウトまでは正常なのですが
繰り返しの
ログインがされません

0

No Answers yet.

Your answer might help someone💌