TypeError:“WebElement”对象不可订阅使用Selenium和Python提交表单时出错

2024-09-30 18:24:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试自动提交twitch剪辑,以获得他在《鳕鱼》上制作的好剧本,但我遇到了一些问题

这是我设置的一个测试表单,它与剪辑正常提交的表单相同-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

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


Tags: namehttpsbrowsersendbykeysfindclass
2条回答

此错误消息

TypeError: 'WebElement' object is not subscriptable

…意味着您向WebElement添加了一个不可下标的索引。索引可用于访问列表的元素


通过类名称()查找元素

^{}按类名在该元素的子元素中查找元素

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


解决方案

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

submitbutton.click()

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

相关问题 更多 >