【问题标题】:Selecting specifically google form dropdown using selenium without select tag in python在python中使用没有选择标签的硒专门选择谷歌表单下拉列表
【发布时间】:2021-03-08 22:30:21
【问题描述】:

我一直在尝试通过 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 类,请不要将此问题标记为重复问题

How to select/get drop down option in Selenium 2

How to select a drop-down menu value with Selenium using Python?

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

Automate Dropdown Menu in Selenium Without Select

【问题讨论】:

    标签: python html selenium drop-down-menu google-forms


    【解决方案1】:

    问题是即使您的 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()
    

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

    【讨论】:

    • 请在端到端运行整个执行后接受答案,以确保它保留使用上述方法填写的表格中的值。
    猜你喜欢
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多