类型错误:'WebElement' 对象不是使用 Selenium 和 Python 提交表单的可订阅错误

问题描述

我正在尝试自动提交 twitch 剪辑以获取他在 cod 上制作的好戏,但遇到了一些问题。

这是我设置的测试表格,与正常提交的剪辑相同 - https://forms.gle/MDMM3buW2DT5erpp8

from selenium import webdriver

option = webdriver.ChromeOptions()
option.add_argument("-incognito")


browser = webdriver.Chrome(executable_path='/Users/Goldilocks/Downloads/chromedriver',options=option)

browser.get("https://forms.gle/MDMM3buW2DT5erpp8")

clipDescription = "streamer sticks juggernaut with semtex for the win!"
clipLink = "https://twitch.tv/joocylad"
textBoxes = browser.find_elements_by_class_name("quantumWizTextinputPaperinputInput")
radiobuttons = browser.find_elements_by_class_name("docssharedWizToggleLabeledLabelWrapper")
submitbutton = browser.find_element_by_class_name("appsMaterialWizButtonPaperbuttonContent")


radiobuttons[3].click()

radiobuttons[2].click()

textBoxes[0].send_keys("JoocyLad")

textBoxes[1].send_keys(clipLink)

textBoxes[2].send_keys(clipDescription)

textBoxes[3].send_keys("email")


submitbutton[0].click()

browser.close()

代码还没有完全完成,我将把 clipLinkclipDescription 变成在程序运行时接受输入的变量,但我还没有解决这个问题。

我遇到的问题是第二个多项选择题没有填写。我也收到错误

Traceback (most recent call last):
  File "/Users/Goldilocks/PycharmProjects/pythonProject/test.py",line 31,in <module>
    submitbutton[0].click()
TypeError: 'WebElement' object is not subscriptable

我使用的是 google chrome 版本 87.0.4280.88,chrome 驱动程序是相同的版本,87.0.4280.88

解决方法

我认为问题在于 find_element_by_class_name() 返回单个项目,而不是列表。删除 [0],它应该可以工作。也看看here

,

这个错误信息...

TypeError: 'WebElement' object is not subscriptable

...表示您已将索引添加到不可下标的 WebElement。索引可用于访问列表的元素。


find_element_by_class_name()

find_element_by_class_name() 按类名在此元素的子元素中查找元素。

由于 find_element_by_class_name() 返回单个元素,它没有索引且不可下标。


解决方案

您需要从 submitbutton[0].click() 行中删除索引。因此,您的有效代码行将是:

submitbutton.click()