【问题标题】:How to Handle Drop-down for Google form using selenium using python如何使用 python 使用 selenium 处理 Google 表单的下拉列表
【发布时间】:2021-06-05 10:58:47
【问题描述】:
有人可以帮助我了解如何在 python 中使用 selenium 来自动化谷歌表单中的下拉菜单。
我面临的问题是我能够找到下拉菜单并选择它,但我无法选择我尝试过的选项select_by_index 但它不起作用。先感谢您。
(我是论坛的新手,如果我以模棱两可的方式提出问题,请见谅)
drop = Select(browser.find_element_by_class_name('quantumWizMenuPaperselectContent').click())
drop.select_by_index(0)
【问题讨论】:
标签:
python
forms
selenium-chromedriver
【解决方案1】:
虽然我认为可能有更好的方法来做到这一点,但我设法做到了:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome("YOUR PATH HERE")
driver.get("YOUR SITE HERE")
driver.find_element(By.CSS_SELECTOR, ".isSelected").click()
# Item 1 in drop down has an ending Div of 3
# Item 2 ending div of 4
# I added the + 2 in the f string so that DROPDOWN_ITEM = 1 Means find for div 3
DROPDOWN_ITEM = 1
dropdown_item_1 = WebDriverWait(driver, 10).until(EC.presence_of_element_located
((By.XPATH, f'//*[@id="mG61Hd"]/div[2]/div/div[2]/div/div/div/div[2]/div/div[2]/div[{DROPDOWN_ITEM} + 2]')))
dropdown_item_1.click()
如果您只想定位第一个项目,可以使用以下内容:
dropdown_item_1 = WebDriverWait(driver, 10).until(EC.presence_of_element_located
((By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]/div/div/div/div[2]/div/div[2]/div[3]')))
dropdown_item_1.click()
【解决方案2】:
不使用 Select ,这是我设法做到的。
由于谷歌表单是 TAB 友好的(即,您可以使用 TAB 键从上到下导航),您可以选择上一个字段并执行 send_keys(Keys.TAB) 以聚焦目标字段...
例子:-
url = "https://docs.google.com/forms/d/e/1FAIpQLScosZjmDrvgUvh77tXsaAb24hKVgaBnjJfJz2BX1PvoqIO1Ow/viewform"
phField = #xpath of phone number field
现在,关注 phField 的下一个字段,并发送所需的选项。
driver.find_element_by_xpath(phField ).send_keys(Keys.TAB,"10.05")
不要忘记从 selenium.webdriver.common.keys 导入密钥