1

Hello guys I'm really a newbie to python and I just writing a piece of code that opens Whatsapp

and you give it the person's name and the message then sends how many times you want.

But when I start debugging the code it gives me this:

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()

guys please someone good at python answer me !!!

IHosseini
  • 31
  • 4
  • 1
    Why don't you look at what type `driver.find_element_by_class_name('_3FRCZ')` has? Then you'll know why you can't index into it. Just `print(type(driver.find_element_by_class_name('_3FRCZ')))` and you'll see what it is. – Tom Karzes Aug 15 '20 at 22:40
  • Does this answer your question? [TypeError: 'WebElement' object is not subscriptable](https://stackoverflow.com/questions/58734107/typeerror-webelement-object-is-not-subscriptable) – Ivan Litteri Aug 15 '20 at 22:44

1 Answers1

1

find_element_by_class_name()

find_element_by_class_name() finds an element by class name.

In the line of code:

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

driver.find_element_by_class_name('_3FRCZ') would return a single WebElement. Hence you won't be able to attach an index to it or in other words make it subscriptable.


Solution

There are two solutions:

  • Remove the index i.e. [1] your code will be all good.

  • As an alternative, instead of driver.find_element_by_class_name() you need to use find_elements_by_class_name(). So effectively your line of code will be:

    msg = driver.find_elements_by_class_name('_3FRCZ')[1]
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • sir thanks for your answer but when I run it again it shows: Exception has occurred: TypeError object of type 'WebElement' has no len() File "E:\Iliya\My Courses\Python\Projects\Whatsapp Robot\Whatsapp_Bot.py", line 17, in msg.send_keys(msg) – IHosseini Aug 15 '20 at 22:57
  • So instead of `[1]` you need `[0]` i.e. the first matched element. – undetected Selenium Aug 15 '20 at 23:00