使用Selenium和Python从下拉日期选择器中选择日期

vc6uscn9  于 2023-02-02  发布在  Python
关注(0)|答案(3)|浏览(293)

我尝试选择不同的日期而不是默认日期(当前日期)。例如,初始页面弹出持股日期: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'

有什么建议吗?

kognpnkq

kognpnkq1#

你也可以使用javascript来设置dat,而不必像以前那样使用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)
mrwjdhj3

mrwjdhj32#

select标记未在HTML DOM中用于此下拉列表。因此,在此情况下不能使用select类。
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,然后点击搜索按钮

f0brbegy

f0brbegy3#

用于在website中选择日期的<input>元素设置了属性 readonly="readonly"

<input type="submit" name="btnSearch" value="Search" onclick="return preprocessMutualMarketMainForm($('#txtShareholdingDate').val());" id="btnSearch" title="Search" class="btn-blue">

溶液
要选择日期,您需要将 readonly 属性和 value 属性分别remove到新的***日期***,如下所示:

driver.get("https://www3.hkexnews.hk/sdw/search/mutualmarket.aspx?t=hk&t=hk&t=hk&t=hk")
element = driver.find_element(By.CSS_SELECTOR, "input#txtShareholdingDate")
driver.execute_script("arguments[0].removeAttribute('readonly')", element)
driver.execute_script("arguments[0].setAttribute('value', '2023/01/31')", element)
driver.find_element(By.CSS_SELECTOR, "input#btnSearch").click()

浏览器快照:

相关问题