如何使用Selenium和Python从GoogleForm非选择下拉菜单中选择选项

问题描述 投票:-1回答:2

我想通过使用python和selenium自动进行选择。我可以按名称选择文本字段,但不确定如何选择表单中的下拉列表。

https://docs.google.com/forms/d/e/1FAIpQLScbs4_3hPNYgjUO-hIa-H1OfJiDZ-FIY1WSk31jGyW5UtQ-Ow/viewform

我尝试通过类来使用send_keys来获取元素,但似乎不起作用。

driver.find_element_by_class_name("quantumWizMenuPaperselectOption freebirdThemedSelectOptionDarkerDisabled exportOption").send_keys("my choice")

如何从上述表格的下拉菜单中选择所需的选项?

python selenium xpath css-selectors webdriverwait
2个回答
0
投票

看来该类返回了多个元素。

.find_element_by_class_name

上面返回它发现的第一个碰巧不起作用的东西。另一种策略是“全部尝试-单击除外”。见下文。

from selenium import webdriver
import time


driver = webdriver.Firefox(executable_path=r'C:\\Path\\To\\Your\\geckodriver.exe')

driver.get("https://docs.google.com/forms/d/e/1FAIpQLScbs4_3hPNYgjUO-hIa-H1OfJiDZ-FIY1WSk31jGyW5UtQ-Ow/viewform")

time.sleep(2)

dropdown = driver.find_element_by_xpath("//div[@role='option']")
dropdown.click()
time.sleep(1)

option_one = driver.find_elements_by_xpath("//div//span[contains(., 'Option 1')]")
for i in option_one:
    try:
        i.click()
    except Exception as e:
        print(e)

0
投票

要选择文本为选项2的选项,必须为element_to_be_clickable()引入WebDriverWait,并且可以使用以下Locator Strategies之一:

  • 使用CSS_SELECTOR

    driver.get('https://docs.google.com/forms/d/e/1FAIpQLScbs4_3hPNYgjUO-hIa-H1OfJiDZ-FIY1WSk31jGyW5UtQ-Ow/viewform')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.quantumWizMenuPaperselectOptionList"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.exportSelectPopup.quantumWizMenuPaperselectPopup div.quantumWizMenuPaperselectOption.freebirdThemedSelectOptionDarkerDisabled.exportOption[data-value='Option 2']"))).click()
    
  • 使用XPATH

    driver.get('https://docs.google.com/forms/d/e/1FAIpQLScbs4_3hPNYgjUO-hIa-H1OfJiDZ-FIY1WSk31jGyW5UtQ-Ow/viewform')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='quantumWizMenuPaperselectOptionList']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='exportSelectPopup quantumWizMenuPaperselectPopup']//div[@class='quantumWizMenuPaperselectOption freebirdThemedSelectOptionDarkerDisabled exportOption' and @data-value='Option 2']//span[text()='Option 2']"))).click()
    
  • :您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
© www.soinside.com 2019 - 2024. All rights reserved.