[英]How to select an option from the GoogleForm non select dropdown using Selenium and Python
我想通過使用 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")
如何從上述表格的下拉列表中選擇我選擇的選項?
看起來這個類返回了多個元素。
.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)
要選擇帶有文本的選項作為選項 2,您必須為element_to_be_clickable()
引入WebDriverWait ,您可以使用以下任一定位器策略:
使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.