`find_elements` メソッドの引数は
タプルで渡す必要がありますが、
現在のコードでは括弧でタプルを作成していないため、
`"using" must be a string` エラーが発生しています。
`find_elements` メソッドの正しい記述方法は以下のようになります。
```python
list_items
= self.driver.find_elements(By.CLASS_NAME, "item")
- 必要に応じて `WebDriverWait` を用いて
要素がレンダリングされるまで待機します。
以下のように変更すれば、
`find_elements` の実行前に十分な待機時間を設けることができます。
```python
list_items = WebDriverWait(self.driver, 15).until(
lambda driver:
driver.find_elements(By.CLASS_NAME, "item")
)
----------------------------------------------------
import time
import threading
import tkinter as tk
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import customtkinter as ctk
from tkinter import filedialog
class TestPokemonCenter:
def __init__(self, email, password):
self.str_email01 = email
self.str_password01 = password
self.driver = None
def login_test01(self):
# Edgeドライバの初期化
service
= Service(EdgeChromiumDriverManager().install())
self.driver
= webdriver.Edge(service=service)
# 正しいURLに修正
self.driver.get(
"url to site")
try:
waiting_room
= WebDriverWait(self.driver, 20).until(
EC.presence_of_element_located(
(By.ID, "lbHeaderP" ))
)
print("Waiting room detected.
Waiting for navigation...")
# 待合室ページの処理
#(例: ボタンをクリックする、一定時間待機するなど)
WebDriverWait(self.driver, 120).until_not(
EC.presence_of_element_located(
(By.ID, "lbHeaderP" ))
)
print("Navigated from waiting room.")
except TimeoutException:
print("No waiting room detected.
Proceeding to login.")
try:
wait = WebDriverWait(self.driver, 8)
# ログイン画面のページへのリンクをクリック
link_to_login = wait.until(
EC.presence_of_element_located(
(By.XPATH,
'//*[@id="wrap"]/header/div[1]/ul/li/a'))
)
link_to_login.click()
# Interact with the text field of mail address
# of the user account
input_email = wait.until(
EC.presence_of_element_located(
(By.XPATH, '//*[@id="login_mail"]'))
)
input_email.click()
input_email.send_keys(self.str_email01)
# Interact with the text field of password
# of the user account
input_password = wait.until(
EC.presence_of_element_located(
(By.XPATH, '//*[@id="login_pass"]'))
)
input_password.click()
input_password.send_keys(self.str_password01)
except Exception as e:
print("Exception occurred:", e)
def main_test01(self, list_to_order):
try:
# Click the submit element, login button
#login_button = WebDriverWait(self.driver, 8).until(
# EC.presence_of_element_located(
(By.XPATH, '//*[@id="login_submit"]'))
#)
#login_button.click()
# ページ遷移後、特定の要素がロードされるのを待つ
# 最大15秒待つ
wait = WebDriverWait(self.driver, 15)
# メインページ特有の要素
main_page_element = wait.until(
EC.presence_of_element_located(
(By.NAME, 'keyword'))
)
#self.deal_order_list(list_to_order)
len_order = len(list_to_order)
for i in range(len_order):
# 検索ボックスの xpath
str_attr_name = 'keyword'
input_main_search_box = wait.until(
EC.presence_of_element_located(
(By.NAME, str_attr_name))
)
input_main_search_box.click()
str_notation = list_to_order[i]
list_str_notation
= str_notation.split( "," )
len_search = len(list_str_notation)
str_format = ""
'''
for str_elm in list_str_notation :
str_format
= str_format + ( str_elm + " " )
'''
for i in range( len_search-1 ) :
str_format
= str_format + ( list_str_notation[i] + " " )
#print( str_format )
input_main_search_box.send_keys( str_format )
main_search_button = wait.until(
EC.presence_of_element_located(
(By.XPATH,
'//*[@id="wrap"]/header/div[2]/ul/li[1]/form/input[3]'))
)
main_search_button.click()
print( "passed 177" )
'''
list_items_temp = wait.until(
EC.presence_of_element_located(
(By.CLASS_NAME, "item "))
)
print( "passed 186" )
'''
time.sleep( 2 )
list_items = self.driver.find_elements((By.CLASS_NAME, "item "))
len_temp = len( list_items )
print( len_temp )
list_a_tag_to_order = []
if len_search < 4 :
print( "length short" )
continue
print( "passed 194" )
except Exception as e:
print("Exception occurred:", e)
def deal_order_list(self, list_to_place_order):
# 最大15秒待つ
wait = WebDriverWait(self.driver, 15)
len_order = len(list_to_place_order)
for i in range(len_order):
str_item_to_order
= list_to_place_order[i]
str_attr_name = 'keyword'
input_main_search_box = wait.until(
EC.presence_of_element_located(
(By.NAME, str_attr_name))
)
input_main_search_box.click()
input_main_search_box.send_keys(str_item_to_order)
main_search_button = wait.until(
EC.presence_of_element_located(
(By.XPATH,
'//*[@id="wrap"]/header/div[2]/ul/li[1]/form/input[3]'))
)
main_search_button.click()
list_items = wait.until(
EC.presence_of_element_located((By.CLASS_NAME, "item"))
)
list_search_notation = str_item_to_order.split()
list_a_tag_to_order = []
len_search = len(list_search_notation)
for i in range(len_search):
str_search_word = list_search_notation[i]
for item in list_items:
p_item_name = item.find_element(By.CLASS_NAME, "name")
item_text = p_item_name.text
list_search_word = str_search_word.split(",")
bool_order
= self.should_place_order(
item_text=item_text,
list_search_word=list_search_word)
if bool_order:
a_tag = item.find_element(By.XPATH, './/a')
str_href = a_tag.text
list_a_tag_to_order.append(str_href)
print(list_a_tag_to_order)
def should_place_order(self, item_text, list_search_word):
bool_has_box = 'Box' in list_search_word
len01 = len(list_search_word)
bool_should_place_order = True
for i in range(len01):
word = list_search_word[i]
if i == 2: # Box のチェック
if bool_has_box:
bool_temp = word in item_text
else:
bool_temp = word not in item_text
if not bool_temp:
bool_should_place_order = False
break
else: # 他の単語のチェック
bool_temp = word in item_text
if not bool_temp:
bool_should_place_order = False
break
return bool_should_place_order
class MyApp(ctk.CTk):
def __init__(self):
super().__init__()
ctk.set_appearance_mode("dark")
self.title("Thread Control")
self.geometry("500x500")
# Label
self.label
= ctk.CTkLabel(
self, text="Pokemon Center Tool",
font=("Arial", 14))
self.label.place(x=180, y=10)
# Entry & TextVar
self.text_var
= ctk.StringVar(
value="galapagosbreeze21@gmail.com")
self.text_var2
= ctk.StringVar(value="febluebird2015")
# Entries
self.entry1
= ctk.CTkEntry(
self, textvariable=self.text_var,
width=220, height=30, border_width=1,
border_color="#FFCC00" )
self.entry1.place(x=20, y=45)
self.entry2
= ctk.CTkEntry(
self, textvariable=self.text_var2,
width=220, height=30, border_width=1
, border_color="#FFCC00" )
self.entry2.place(x=250, y=45)
# ボタン: recaptchaまでの動作
self.btn_action01 = ctk.CTkButton(
master=self,
text="ログイン 01",
border_width=1, # ボーダー幅
border_color="#4578C1", # ボーダー色
fg_color="#353535",
text_color="#EEEEEE",
width=450,
height=30,
command=self.run_login_thread01
)
self.btn_action01.place(x=20, y=95)
self.txt_content = ""
self.btn_file_picker = ctk.CTkButton(
self ,
command = self.load_txt_file,
text="TXTの読込",
#bg="blue",
# ボタンの背景色をRGB (200, 120, 200)に設定
fg_color="#6B45D2",
text_color="white",
width=160,
height=30
)
self.btn_file_picker.place(x=20, y=140)
self.text_area_csv_content
= ctk.CTkTextbox(
#frame_content, width=560, height=150
self,
# テキストボックスの背景色
#fg_color="white",
text_color="white",
# 角の丸み(任意)
corner_radius=10,
width=450,
height=110
)
self.text_area_csv_content
.place(x=20, y=190)
# ボタン: recaptcha以後の動作
self.btn_action02 = ctk.CTkButton(
master=self,
text="ログイン 02",
# ボーダー幅
border_width=1,
# ボーダー色
border_color="#4578C1",
fg_color="#353535",
text_color="#EEEEEE",
width=450,
height=30,
command=self.run_task_thread02
)
self.btn_action02.place( x=20, y=315 )
self.text_area_report = ctk.CTkTextbox(
#frame_content, width=560, height=150
self,
# テキストボックスの背景色
#fg_color="white",
text_color="white",
# 角の丸み(任意)
corner_radius=10,
width=450,
height=110
)
self.text_area_report.place( x=20, y=380 )
# ボタン1: TXTの読み込み
def load_txt_file( self ):
file_path = filedialog.askopenfilename(
title="TXTファイルを選択してください",
filetypes=[("テキストファイル", "*.txt")]
)
if file_path:
with open(
file_path, "r", encoding="utf-8") as file:
self.txt_content = file.read()
self.text_area_csv_content.delete(
"1.0", ctk.END)
self.text_area_csv_content.insert(
ctk.END, self.txt_content)
def run_login_thread01(self):
str_email = self.entry1.get()
str_password = self.entry2.get()
self.demo_class
= TestPokemonCenter(email=str_email,
password=str_password)
thread
= threading.Thread(
target=self.demo_class.login_test01)
thread.start()
#
#
#
# end of class MyApp
def run_task_thread02(self):
str_order_content
= self.text_area_csv_content.get("1.0", "end-1c")
list_to_order = str_order_content.splitlines()
#print( list_to_order )
thread
= threading.Thread(
target=self.demo_class.main_test01,
args=( list_to_order, )) #args=([],))
thread.start()
#
#
#
# end of class MyApp
if __name__ == "__main__":
app = MyApp()
app.mainloop()
上記の selenium with pythonのコードを実行してみると
print( "passed 177" )
は実行されたのですが、
print( len_temp )
は表示されずに
"using" must be a string というエラーが表示されました。
そのあいだの
self.driver.find_elementsのコーディングに
不具合があるのでしょうか?
修正できるのであれば、その手法を教えていただけないでしょうか?
エラーの原因は以下のコード部分にあります。
```python
list_items
= self.driver.find_elements(
(By.CLASS_NAME, "item "))
```
`find_elements` メソッドの引数は
タプルで渡す必要がありますが、
現在のコードでは括弧でタプルを作成していないため、
`"using" must be a string` エラーが発生しています。
`find_elements` メソッドの正しい記述方法は以下のようになります。
```python
list_items
= self.driver.find_elements(By.CLASS_NAME, "item")
```
また、`.find_elements()` メソッドは
エレメントをリストとして返します。
エラーが解消した後、このリストを処理して目的の動作を確認することができます。
### 修正後のコード
修正した該当部分は次のようになります。
```python
try:
list_items
= self.driver.find_elements(
By.CLASS_NAME, "item")
len_temp = len(list_items)
print(len_temp)
except Exception as e:
print(
"Exception occurred
while finding elements:", e)
```
### 修正後の全体的な流れ
1. `find_elements` メソッドの引数を修正。
2. 修正後、取得した要素リストの長さを
`len()` で計算し、`print()` で出力。
3. エラーが発生した場合の例外処理
(`Exception` ブロック) を入れて、デバッグに役立てる。
### 追加の確認ポイント
- `CLASS_NAME` の値が正しいかどうか確認してください
(`"item"` で正しいのか)。
- 必要に応じて `WebDriverWait` を用いて
要素がレンダリングされるまで待機します。
以下のように変更すれば、
`find_elements` の実行前に十分な待機時間を設けることができます。
```python
list_items = WebDriverWait(self.driver, 15).until(
lambda driver: driver.find_elements(By.CLASS_NAME, "item")
)
```
この修正でエラーが解消され、
目的の動作が実現できるはずです。試してみてください!
コメント
コメントを投稿