python - 在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 类,请不要将此问题标记为重复问题
如何使用 Python 使用 Selenium 选择下拉菜单值?
使用 webdriverwait 似乎也没有达到这篇文章中详述的技巧:
解决方案
问题是即使您的 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()
请注意,由于我没有提交表单,因此我尚未验证这种选择方式是否保留了表单中的信息。你可以测试它来验证它。
推荐阅读
- java - 我可以从 /info/{login} 获得价值吗?
- html - 将图标移至列表左侧
- firebase - 提供者从流中获取价值的延迟
- python - 在我的绘图上格式化 DateTime 轴(Python)
- android - 在 kotlin android 中使用 var 或 val?
- mysql - 如何在 MySQL 中使用 LIKE 而不删除清理?
- django - Django Heroku 部署未找到模块
- python - Django静态文件未加载
- debugging - JetBrains Rider 不评估表达式
- reactjs - Next.js 可以从 Asp.Net Core API 获取数据吗?