简体   繁体   English

我如何执行javascript以使用python和selenium更改日期

[英]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. 我是selenium和javascript的新手,但是我试图编写Python来更改体育比赛日期的日期。 The scoreboard page has a < MM/DD/YYYY > at the top. 记分牌页面的顶部是<MM / DD / YYYY>。 The "current" date (01/05/2018 opens as the default when the page is loaded) is in the middle and < & > have: “当前”日期(加载页面时默认为01/05/2018打开)在中间,并且<&>具有:

    <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: 在html的前面,该站点具有:

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

In Python I have tried: 在Python中,我尝试过:

    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(). 您的代码不起作用,因为您必须在driver.execute_script()中发送changeDate(val)的参数val。

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! 感谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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