如何使用 selenium 从 Google Sheets 下载 CSV 格式的电子表格?特别是,如何点击最后的 CSV 子选项?

问题描述 投票:0回答:1

我正在尝试使用 selenium 下载谷歌电子表格。其想法是单击“文件”菜单栏,然后单击“下载”子菜单,最后单击“逗号分隔值 (.csv)”子选项。

我已经配置了 webdriver 来下载文件(设置默认下载目录、禁用提示等)并避免被 google 阻止(我正在使用带有代理的未检测到的 chromedriver),并且我已成功单击文件菜单栏和下载子菜单,但我无法弄清楚如何单击 CSV 子选项。

这是我到目前为止所拥有的:

driver = get_driver() # a function that sets up a chromedriver instance with a bunch of options
driver.get(r"https://docs.google.com/spreadsheets/d/10X0-CCSv7FenZP1YaKlDSE-PD4LSZAgpzT5Rs9F8hvA/")

# click the file menu (this works)

file_element = WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.ID, "docs-file-menu")))
ActionChains(driver).move_to_element(file_element).click().perform()

# click the download submenu (this works too)

download_element = WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.ID, ":8i")))
ActionChains(driver).move_to_element(download_element).click().perform()

# click the csv element (I'm not sure how to do this)

# ...?

找到“文件”菜单栏的 CSS 选择器非常简单。我必须使用“在调试器中暂停”选项来检查“下载”子菜单。但我无法找到文件类型子选项的 CSS 选择器,因为无法检查。

有人知道如何点击这个吗?

python selenium-webdriver google-sheets web-testing
1个回答
0
投票

您可以通过打开开发工具在调试模式下停止执行并使用下拉项搜索文本来找到下拉项。

第二个选项 - 您可以定义表示与您的项目完全或部分匹配的文本的选择器。

我写了组合方法:下载项目有选择器

[id=':8i']
和 您可以通过xPath表达式找到.csv子菜单选项
//*[contains(.,'csv')]

driver = webdriver.Chrome()
driver.get(r"https://docs.google.com/spreadsheets/d/10X0-CCSv7FenZP1YaKlDSE-PD4LSZAgpzT5Rs9F8hvA/")
action_chains = ActionChains(driver)
wait = WebDriverWait(driver, 10)
file_element = wait.until(EC.element_to_be_clickable((By.ID, "docs-file-menu")))
action_chains.move_to_element(file_element).click().perform()
download = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "[id=':8i']")))
action_chains.move_to_element(download).perform()
wait.until(EC.visibility_of_element_located((By.XPATH, "//*[contains(.,'csv')]"))).click()
© www.soinside.com 2019 - 2024. All rights reserved.