我想通过使用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")
如何从上述表格的下拉菜单中选择所需的选项?
答案 0 :(得分: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)
答案 1 :(得分:0)
要选择文本为选项2 的选项,您必须为element_to_be_clickable()
引入 WebDriverWait ,并且可以使用以下任何一种{{3} }:
使用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