Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

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:IliyaMy CoursesPythonProjectsWhatsapp RobotWhatsapp_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 !!!????

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...