Wystąpił wyjątek: obiekt TypeError „WebElement” nie jest indeksowany

Aug 16 2020

Witam, naprawdę jestem nowicjuszem w Pythonie i właśnie piszę fragment kodu, który otwiera Whatsapp

i podajesz mu imię i nazwisko osoby, a następnie wiadomość wysyła, ile razy chcesz.

Ale kiedy zaczynam debugować kod, daje mi to:

Exception has occurred: TypeError 'WebElement' object is not subscriptable File "E:\Iliya\My Courses\Python\Projects\Whatsapp Robot\Whatsapp_Bot.py", line 15, in <module> msg = driver.find_element_by_class_name('_3FRCZ')[1]

# ======================================
from selenium import webdriver
PATH = 'C:\\Program Files (x86)\\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get('https://web.whatsapp.com/')

input("Please Press The 'Enter' Button... ")
name = input("Enter Person's Name: ")
msg = input("Enter The Message: ")
counter = int(input("How Many Times Do You Want To Repeat The Message?:  "))

user = driver.find_element_by_xpath('//span[@title = "{}"]'.format(name))
user.click()
msg = driver.find_element_by_class_name('_3FRCZ')[1]
for i in range(counter):
    msg.send_keys(msg)
    button = driver.find_element_by_class_name('_1U1xa')[0]
    button.click()

chłopaki, proszę, ktoś dobry w Pythonie, odpowiedz mi !!! 🙏🙏

Odpowiedzi

1 DebanjanB Aug 16 2020 at 05:47

find_element_by_class_name ()

find_element_by_class_name() znajduje element według nazwy klasy.

W linii kodu:

msg = driver.find_element_by_class_name('_3FRCZ')[1]

driver.find_element_by_class_name('_3FRCZ')zwróci pojedynczy element WebElement . Dlatego nie będziesz w stanie dołączyć do niego indeksu lub innymi słowy, uczynić go indeksowanym.


Rozwiązanie

Istnieją dwa rozwiązania:

  • Usuń indeks, czyli cały [1]kod będzie dobry.

  • Alternatywnie, zamiast tego driver.find_element_by_class_name()musisz użyć find_elements_by_class_name(). W efekcie Twój wiersz kodu będzie wyglądał następująco:

    msg = driver.find_elements_by_class_name('_3FRCZ')[1]