javascript - 如何在 Python 中使用 Selenium chromedriver 单击按钮
问题描述
嗨,伙计们(对不起,我的英语提前了),我想单击一个按钮以从此页面下载文件https://myterna.terna.it/SunSet/Public/Pubblicazioni?filter.IdSezione=585AF7EFCA196EBBE0532B889B0A6372。这是我的简单代码:
download_dir = 'C:/Users/Francesco.Borri/Desktop/Sunset'
options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : download_dir}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(options=options)
driver.get('https://myterna.terna.it/SunSet/Public/Pubblicazioni?filter.IdSezione=585AF7EFCA196EBBE0532B889B0A6372')
container1 = driver.find_element_by_class_name("row") #Until this class is OK
container2 = driver.find_element_by_class_name("col-sm-12 table-wrapper") # From this class NOPE
#button = container.find_element_by_class_name(CLASS_OF_THE_BUTTON)
#button.click()
该代码正确打开了页面,但它无法找到我正在寻找的所有类(其中一个里面有我珍贵的按钮)。我研究了 html 页面源代码,发现最初缺少的类是在页面加载时从脚本(下面的屏幕截图)创建的。我不熟悉 Javascript 和 Ajax。有没有办法找到并点击我珍贵的按钮?
PS:现在文件已下载,但出现此未定义错误。我什至尝试手动下载它,但我收到了同样的错误。看来我的 chromedriver 没有下载文件的权限。
解决方案
由于页面上有许多下载按钮,因此您需要在查找按钮时指定要下载的出版物的标题。还建议WebDriverWait
在您尝试单击的元素上调用,以确保在与它交互之前它是可见的:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
download_dir = 'C:/Users/Francesco.Borri/Desktop/Sunset'
options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : download_dir}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(options=options)
driver.get('https://myterna.terna.it/SunSet/Public/Pubblicazioni?filter.IdSezione=585AF7EFCA196EBBE0532B889B0A6372')
# Article name is "Prezzi Giornalieri Marginale Quarto Orari 20191111"
# wait on the download button for this article to exist
download_button = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//tr[td/span[text()='Prezzi Giornalieri Marginale Quarto Orari 20191111']]/td/div/a[contains(@class, 'download')]")))
# click the link to download
download_button.click()
推荐阅读
- node.js - 优化MongoDB中的聚合
- java - 如何表示一个长于 long 的数字并打印出来
- java - 范围内的代理模式
- c - free pointer by other pointer points same memory
- c# - Direct2D,WPF D3D10 图像在调整大小时模糊
- node.js - 在 Dockerfille 上运行 Angular 通用应用程序
- javascript - 如何在 img src 中指定图像本地路径以在 react/JavaScript 中加载
- c++ - CGAL构造球面多面体
- mysql - mysql中的类型转换层次结构是什么?
- java - 未能执行目标 org.openjfx:javafx-maven-plugin:0.0.4。我从 Fxml 文件开始,我无法将它们附加到控制器