#python #selenium
Вопрос:
У меня есть эта функция ниже. Он создает список заметок. Ни одна заметка в этом конкретном списке не соответствует выражению. Поэтому функция должна открыть окно сообщения (поскольку в этом случае заметок не будет найдено) и завершить функцию возвращением. Но вместо этого он выдает код блока except. И почему не выводятся операторы печати, которые находятся перед ошибкой? Разве код не читается построчно?
def report():
# function to click on the first occurrence of a report in the note list
try:
global clicked # To create a global variable inside a function, you can use the global keyword.
clicked = "false" # set default state to false
notesList = WebDriverWait(driver, 20).until(
EC.presence_of_all_elements_located((By.XPATH, relativeXpathNotes))) #creates list with 10 notes
print(notesList)
print("test before next button code")
nextButton = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, xpathNextButton)))
print("this is the element for next-button: ", nextButton)
print("test after next button code")
isEnabled = nextButton.is_enabled() # Check if element is actually clickable. This will return true if the button is clickable.
print("Is the button clickable?: ", isEnabled)
found = False # set default state to false
patternForFindingNote = r"notes"
# start the first for loop
for note in notesList:
match = re.search(patternForFindingNote, note.text) #if match then click on the element/item
if match:
print("The note to be clicked is: ", note.text)
note.click()
found = True
break
print("test before popup")
if ((not found) and (not isEnabled)): # this is the code that I expect to trigger if no match/notes is found. if not found any notes and the next button is not clickable, then there is no more notes to be found.
print("No more notes found in this first list of notes. You have signed all reports. Good work!")
# pop up message box
messagebox.showinfo("Good work!", "No more notes found. You have signed all reports.")
return # you can use the return statement without any parameter to exit a function. Exit the function if no more weekly/monthly notes are found.
print("test after popup")
if(not found) and isEnabled: # if not found in the whole loop (after all iterations) and if the next button is truly clickable (i.e. there is more items on the next page) then click next button
isClicked(xpathNextButton) # this function should click on the next button and then return clicked as True
except TimeoutException:
print("Failed to load elementItem")
# code to get the actual note type string from the match above, e.g. "report 2"
global fullstring
fullstring = match.group()
print("The fullstring from match.group() is: ", fullstring)
На выходе получается:
[<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="e0a0b70e-7e2a-40ff-b688-f292877ba4b7", element="72d612d5-105c-4d96-b1b3-b43de7dcb02e")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="e0a0b70e-7e2a-40ff-b688-f292877ba4b7", element="4811db69-329d-4153-beef-0a615163d29f")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="e0a0b70e-7e2a-40ff-b688-f292877ba4b7", element="bf376a4c-d38e-4f76-8e29-a6977849a1f3")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="e0a0b70e-7e2a-40ff-b688-f292877ba4b7", element="cfb83654-9541-4c89-9430-a5179c5b7b57")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="e0a0b70e-7e2a-40ff-b688-f292877ba4b7", element="0f20091b-6802-4bb2-b09f-aa7207e82bdd")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="e0a0b70e-7e2a-40ff-b688-f292877ba4b7", element="de32e469-a305-4b95-bd77-71b5e249839e")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="e0a0b70e-7e2a-40ff-b688-f292877ba4b7", element="673268e1-cf6c-4d42-b056-e1771766006f")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="e0a0b70e-7e2a-40ff-b688-f292877ba4b7", element="df7b9e51-f321-49ca-a4a7-a5d4475741a9")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="e0a0b70e-7e2a-40ff-b688-f292877ba4b7", element="79acc1ca-88e5-4c0f-8f01-045f1c16be99")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="e0a0b70e-7e2a-40ff-b688-f292877ba4b7", element="41ce3a7e-a8c7-4331-a1e5-d3bcaec25010")>]
test before next button code
Failed to load elementItem
Exception in Tkinter callback
Traceback (most recent call last):
File "C:UsersKAANAppDataLocalProgramsPythonPython39libtkinter__init__.py", line 1884, in __call__
return self.func(*args)
File "W:test.py", line 2813, in clicker1
report()
File "W:test.py", line 279, in report
fullstring = match.group()
UnboundLocalError: local variable 'match' referenced before assignment
Я проверил, что xpath для следующей кнопки правильный. Почему не выводятся операторы печати, например » печать(«тест после кода следующей кнопки»)»? Код перед этой операцией печати должен работать.
Ответ №1:
Здесь это не удается fullstring = match.group()
, потому что вы используете match
перед созданием такой ссылки ПЕРЕД вызовом .group()
метода.
Несмотря на то, что ты творишь match
здесь:
for note in notesList:
match = re.search(patternForFindingNote, note.text) #if match then click on the element/item
if match:
print("The note to be clicked is: ", note.text)
note.click()
found = True
break
Ваш код не достигает этого утверждения, потому что вы wait
генерируете исключение, поэтому остальная часть кода пропускается.
Комментарии:
1. Спасибо. Решил эту проблему с помощью этого кода
if match: #if there is no match, then match.group code won't work so assign fullstring only if there is a match. global fullstring fullstring = match.group() print("The fullstring from match.group() is: ", fullstring)