简体   繁体   中英

Python Selenium Select date in calendar for start date and end date

I am trying to select start date and end date from the datepicker, and I tried for start date:

driver.get('http://www.chinamoney.com.cn/chinese/zjfxzx/?tbnm=%E6%9C%80%E6%96%B0&tc=null&isNewTab=1')
driver.implicitly_wait(10)
driver.refresh()
driver.implicitly_wait(10)
datefield = driver.find_element_by_id('pdbp-date-1').send_keys("2021-01-05")

But calendar just drop down but does not click, how could I select the start date and then end date from the calendar? besides how could it wait until calendar element shows up?

Thanks in advance!

Simply adding an useragent causes it work correctly. Goalie was hinting at bot detection and it wasn't running the Jquery.

from selenium.webdriver.chrome.options import Options
options = Options()
from fake_useragent import UserAgent
ua = UserAgent()
a = ua.random
user_agent = ua.random
print(user_agent)
options.add_argument(f'user-agent={user_agent}')
driver = webdriver.Chrome(options=options)

Here's a random useragent

options.add_argument("user-agent=Mozilla/5.0 (X11; Ubuntu; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2919.83 Safari/537.36")

Now to the code. If it's a JQuery date picker object you have to click and select your date. Year->Month->Day is the order you want to click. If you aren't allowed to use Select then just click the tag and xpath down to the options whose value is 1 or text is your value. /option[text()='January'] and so forth.

from selenium.webdriver.support.select import Select
wait = WebDriverWait(driver, 5)
driver.get('http://www.chinamoney.com.cn/chinese/zjfxzx/?tbnm=%E6%9C%80%E6%96%B0&tc=null&isNewTab=1')
datefield = wait.until(EC.element_to_be_clickable((By.ID, "pdbp-date-1")))
datefield.click()
##<select class="ui-datepicker-year" data-handler="selectYear" data-event="change"></select>
select = Select(wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "ui-datepicker-year"))))
select.select_by_visible_text("2020")
##<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change"></select>
select2 = Select(wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "ui-datepicker-month"))))
select2.select_by_value("1")
day=1
wait.until(EC.element_to_be_clickable((By.XPATH, "//td[@data-handler='selectDay']/a[text()='{}']".format(str(day))))).click()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM