【问题标题】:Select Date from Dropdown with Selenium and Python使用 Selenium 和 Python 从下拉列表中选择日期
【发布时间】:2023-02-02 20:04:20
【问题描述】:

我试图选择不同的日期而不是默认日期(当前日期)。例如,初始页面弹出持股日期:2023/02/01,但我想从下拉菜单中选择不同的日期,比如 2022/12/23。我的环境是:Selenium 4.3.0 和 Python 3.9.7,Chrome

以下是我的代码:

    url = "https://www3.hkexnews.hk/sdw/search/mutualmarket.aspx?t=hk&t=hk&t=hk&t=hk"
    driver = webdriver.Chrome()
    driver.get(url)
    select_element = driver.find_element(By.XPATH, "//input[@name='txtShareholdingDate']").click()
# The above pop up the required page with Date dropdown, tried different code to select the date but failed. My codes are:

    action = ActionChains(select_element)
    action.send_keys("2023",Keys.ARROW_DOWN)
    action.send_keys("1",Keys.ARROW_DOWN)
    action.send_keys("31",Keys.ARROW_DOWN)
    action.send_keys(Keys.ENTER)
    action.perform()
# AttributeError: 'NoneType' object has no attribute 'execute'

# Also tried
    select = driver.find_element(By.ID, "txtShareholdingDate")
    select.select_by_value("2023/01/31")
    driver.find_element(By.ID, 'btnSearch').click()
# AttributeError: 'WebElement' object has no attribute 'select_by_value'

# Any suggestions ? 

【问题讨论】:

  • 对于错误 - “AttributeError: 'WebElement' object has no attribute 'select_by_value'” - 你必须修改行 - select = Select(driver.find_element(By.ID, "txtShareholdingDate")) ,并添加导入 -从 selenium.webdriver.support.select 导入选择

标签: python selenium


【解决方案1】:

您还可以使用 javascript 设置日期,而不必像您一样使用 ActionChains 设置日期。这也更快,更不容易出错

        newDate = "2023/01/18"
        dateElement = wait.until(EC.presence_of_element_located((By.XPATH,"//input[@name='txtShareholdingDate']")))
        print(dateElement .get_attribute("value"))
        driver.execute_script("arguments[0].setAttribute('value',arguments[1])", dateElement , newDate )
        time.sleep(5)

【讨论】:

    【解决方案2】:

    select 标记未在 HTML DOM 中使用。因此,在这种情况下不能使用 select class。

    driver.find_element(By.XPATH, "//input[@name='txtShareholdingDate']").click()

    在上面一行之后,只需尝试以下代码:

    driver.find_element(By.XPATH, "//button[@data-value='2022']").click()
    driver.find_element(By.XPATH, "//button[@data-value='11']").click()
    driver.find_element(By.XPATH, "//button[@data-value='23']").click()
    driver.find_element(By.ID, "btnSearch").click()
    

    以上 4 行将单击下拉值 2022、11、23,然后单击“搜索”按钮

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多