Exception has occurred: TypeError 'WebElement' object is not subscriptable

ぐ巨炮叔叔 提交于 2021-02-15 07:35:17

问题


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 !!!🙏🙏


回答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]
    


来源:https://stackoverflow.com/questions/63431391/exception-has-occurred-typeerror-webelement-object-is-not-subscriptable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!