【问题标题】:Exception has occurred: TypeError 'WebElement' object is not subscriptable发生异常:TypeError 'WebElement' 对象不可下标
【发布时间】:2020-08-16 06:53:26
【问题描述】:

大家好,我真的是 python 的新手,我只是编写了一段代码来打开 Whatsapp

然后你给它这个人的名字,然后你想要的消息发送多少次。

但是当我开始调试代码时,它给了我这个:

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

请各位擅长python的人回答我!!!????????

【问题讨论】:

  • 你为什么不看看driver.find_element_by_class_name('_3FRCZ')有什么类型?然后你就会知道为什么你不能索引它。只需print(type(driver.find_element_by_class_name('_3FRCZ'))),您就会知道它是什么。

标签: python selenium selenium-webdriver webdriver


【解决方案1】:

find_element_by_class_name()

find_element_by_class_name() 按类名查找元素。

在代码行中:

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

driver.find_element_by_class_name('_3FRCZ') 将返回一个 WebElement。因此,您将无法为其附加索引,或者换句话说,使其可下标。


解决方案

有两种解决方案:

  • 删除 index[1] 你的代码会很好。

  • 作为替代方案,您需要使用find_elements_by_class_name() 而不是driver.find_element_by_class_name()。因此,您的代码行将是:

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

【讨论】:

  • 先生,感谢您的回答,但是当我再次运行它时,它显示:发生异常:“WebElement”类型的 TypeError 对象没有 len() 文件“E:\Iliya\My Courses\Python\ Projects\Whatsapp Robot\Whatsapp_Bot.py",第 17 行,在 msg.send_keys(msg)
  • 所以你需要[0]而不是[1],即第一个匹配的元素。
猜你喜欢
  • 2020-03-03
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 2020-11-09
  • 2020-08-18
  • 1970-01-01
  • 2016-07-20
  • 1970-01-01
相关资源
最近更新 更多