在python 3中使用selenium选择日历上的日期

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

在尝试让 chromedriver 在 selenium 中选择日历中的日期时,我遇到了日期的隐藏字段。 我使用了以下代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException


url = "https://www.fpi.nsdl.co.in/web/Reports/Archive.aspx"
date_value = '2024-06-04'

driver = webdriver.Chrome()
driver.get(url)

try:
    date_button = driver.find_element(By.XPATH, '//*[@id="hdnDate"]')
    driver.execute_script("arguments[0].removeAttribute('type')", date_button)
    uh_date_button = driver.find_element(By.XPATH, '//*[@id="hdnDate"]')
    driver.execute_script("arguments[0].setAttribute('value', arguments[1])", uh_date_button, date_value)
    date_button.click()
    
    # Click on the "view report" button
    view_report_button = driver.find_element(By.XPATH, '/html/body/form/div[3]/div[2]/div[4]/table/tbody/tr[1]/td[3]/a[1]/div[2]')
    view_report_button.click()

    # Click on the "export to excel" button
    export_button = driver.find_element(By.XPATH, '/html/body/form/div[3]/div[2]/div[4]/table/tbody/tr[1]/td[3]/a[2]/div[2]')
    export_button.click()

except TimeoutException:
    print("Timed out waiting for page elements to load")
    
finally:
    driver.close()
    driver.quit()

它卡在日历中并且不执行任何操作

我希望能够在日历上选择一个日期并填充页面。上面给出了我的非工作代码

python-3.x selenium-webdriver web-scraping
1个回答
0
投票

检查下面的工作代码及其内联解释:

import time
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


url = "https://www.fpi.nsdl.co.in/web/Reports/Archive.aspx"

driver = webdriver.Chrome()
driver.get(url)
wait = WebDriverWait(driver, 10)

# Below 2 lines will click on calendar icon and click on 11th of current month
wait.until(EC.presence_of_element_located((By.ID, "imgtxtDate"))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//table[@class='DynarchCalendar-bodyTable']//div[text()='11']"))).click()

# Click View Report
wait.until(EC.element_to_be_clickable((By.ID, "btnSubmit1"))).click()

# Click Export to Excel
wait.until(EC.element_to_be_clickable((By.ID, "btnExcel"))).click()
time.sleep(10)
© www.soinside.com 2019 - 2024. All rights reserved.