简体   繁体   中英

How can I execute javascript to change a date with python and selenium

I'm new to selenium and javascript but I'm trying to write Python that will change a date for sports results. The scoreboard page has a < MM/DD/YYYY > at the top. The "current" date (01/05/2018 opens as the default when the page is loaded) is in the middle and < & > have:

    <a href="javascript:changeDate('01/05/2018');"><</a>
    " 01/05/2018 " 
    <a href="javascript:changeDate('01/07/2018);">></a> ==$0

    <form name="params_form" action="/team/schedule_list" method="post">
    <input id="params_form_schedule_date" type="hidden" name="schedule_date"
    value="01/05/2018"> == $0
    </form>

Earlier in the html the site has:

    <script language="javascript">
            function changeDate(val){
                $('#params_form_schedule_date').val(val);
                document.params_form.submit();
            }

In Python I have tried:

    date = input ('Enter Date (mm/dd/yyyy): ')

    driver.execute_script('changeDate()', date)

    driver.execute_script('''
        var date = arguments[0];
        changeDate().value;''', date)

I've tried a few others too but nothing works. The loading circle will show that something is happening, but the default date does not change. Any help here would be appreciated. (Also I tried to follow the proper formatting here, but I apologize for any mistakes, it's my first time posting).

Your code does not work because you have to send the paremeter val of changeDate(val) in the driver.execute_script().

You can do as follows:

date = '02/05/2018'
driver.execute_script("changeDate('{}')".format(date)) # Just pay attention to the " and the ' in the command

Hope it helps

input_date = <date in format expected>
return_val = driver.execute_script("return changedate(arguments[0])", input_date)

This helps you avoid all the nuances working with a strings or " or '.

I ended up solving this with:

date = input ('Enter Date (mm/dd/yyyy): ')
element=driver.find_element_by_css_selector("input[id=params_form_schedule_date]")
driver.execute_script('arguments[0].setAttribute("value", "%s")' % date, element)
element.submit()

Thanks to all for the help!

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