首页 > 解决方案 > 在python中使用没有选择标签的硒专门选择谷歌表单下拉列表

问题描述

我一直在尝试找到一种通过 selenium 和 python 从谷歌表单中选择下拉选项的方法,但到目前为止还没有成功。

我尝试了几种方法,包括 Select 类(由于下拉表单不使用 select 标签,它不起作用)。以及 XPATH。但是只能单击下拉列表,但无法选择所述下拉列表中的选项。任何帮助将不胜感激!

我需要能够根据各种选项中的文本/值来指定要选择的下拉选项。

代码:

browser.find_element_by_xpath("//div[@class='quantumWizMenuPaperselectOptionList']").click() 
browser.find_element_by_xpath("//div[@class='freebirdThemedSelectOptionDarkerDisabled']/div[@class='quantumWizMenuPaperselectOption'][@data-value='1.05pm - 3.55pm']").click()

我得到的错误是没有找到这样的元素,即使这是我通过相应地检查下拉菜单找到的 XPATH。

我在这里创建了一个示例表单以供参考:https ://forms.gle/prBMqgVVFNv5KWQQA

这些没有帮助,因为它使用 Select 类,请不要将此问题标记为重复问题

如何在 Selenium 2 中选择/获取下拉选项

如何使用 Python 使用 Selenium 选择下拉菜单值?

使用 webdriverwait 似乎也没有达到这篇文章中详述的技巧:

在没有选择的情况下自动化 Selenium 中的下拉菜单

标签: pythonhtmlseleniumdrop-down-menugoogle-forms

解决方案


问题是即使您的 xpath 正确,选择框也不会弹出,直到您将鼠标悬停在该元素上,悬停在该元素上使其可点击。您可以使用下面的代码将鼠标悬停在该选择框元素上,然后尝试单击并选择元素

selectBox = WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.XPATH, "//div[@role='listbox']")))
action = ActionChains(browser);
action.move_to_element(selectBox).perform()

完整代码在这里:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

browser = webdriver.Chrome()
url = 'https://docs.google.com/forms/d/e/1FAIpQLScosZjmDrvgUvh77tXsaAb24hKVgaBnjJfJz2BX1PvoqIO1Ow/viewform'
text = '1.05pm-3.55pm'
browser.maximize_window()
browser.get(url)
selectBox = WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.XPATH, "//div[@role='listbox']")))
action = ActionChains(browser);
action.move_to_element(selectBox).perform()
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@role='listbox']")))
selectBox.click()

selectionXpath = "//div[@class='exportSelectPopup quantumWizMenuPaperselectPopup appsMaterialWizMenuPaperselectPopup']//span[@class='quantumWizMenuPaperselectContent exportContent' and text()='"+text+"']"
selection = WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.XPATH, selectionXpath)))
selection.click()

请注意,由于我没有提交表单,因此我尚未验证这种选择方式是否保留了表单中的信息。你可以测试它来验证它。


推荐阅读