如何匹配基于datetime.date.today()的当前日期?

时间:2016-09-23 14:40:50

标签: python string selenium selenium-webdriver

大家好!我在匹配两个字符串时遇到了一些麻烦。

所以,我从我正在测试的页面中获得了这个HTML代码:

<td class="fixedColumn ng-binding" 
ng-style="{'padding':'5px','line-height':'10px'}" style="padding: 5px; line-height: 10px;">

(today's date: 2016-09-23)

</td>

页面中显示的实际字符串为(今天的日期:2016-09-23)

我尝试使用Python做的是:

#check if today's date = current date
currentDate = datetime.date.today().strftime("(today's date: %Y-%m-%d)")
todayDate = driver.find_element_by_xpath("//td[contains(text(), 'currentDate']")
allOk = 'all good!'
notOk = 'still not OK...'
if todayDate == currentDate:
    print(allOk)
    home = driver.find_element_by_xpath("//a[@title='Home']").click()
else:
    print(notOk)
    driver.close()

根据driver.close(),当我运行脚本时,会发生什么,浏览器会关闭,但是我需要shell来打印'all good!'在shell中,浏览器通过“点击”转到“Home”。

我是Python的新手,但就我而言,我尽一切努力使这项工作成功。任何人都可以给我一些提示并指出我所缺少的东西吗?谢谢:))

2 个答案:

答案 0 :(得分:1)

todayDate = driver.find_element_by_xpath("//td[contains(text(), 'currentDate']")

currentDate周围的引号使得XPath引用的内容包含实际文本&quot; currentDate&#39;,而不是currentDate变量引用的文本,您需要将其更改为:

todayDate = driver.find_element_by_xpath("//td[contains(text(), " + currentDate + "]")

你可能还需要在str(currentDate)中包含currentDate以确保它被转换为字符串,这是我曾经面临的一个问题。

&#39; +&#39;在python中将字符串连接在一起,因此这应该使它查找变量引用的文本。希望这能为你解决它!

另一种不使用Jon Clements建议的python变量的方法:

您可以通过使用字符串格式来更清楚,例如:

"//td[contains(text(), {})]".format(date.today())

只需确保之前有一个来自日期时间的导入日期......

答案 1 :(得分:0)

好的,自从我添加评论以来已经过了大约10分钟,但我已经让它发挥了作用。 以前的代码:

todayDate = driver.find_element_by_xpath("//td[contains(text(), 
" + str(currentDate) + ")]")

之后的代码:

todayDate = driver.find_element_by_xpath("//td[contains(text(), 
'" + str(currentDate) + "')]")

我将" + str(currentDate) + "放入''。另外,我改变了

`if todayDate == currentDate:` to `if todayDate:`

现在按预期工作,我只需要弄明白为什么:)无论如何,谢谢AntlerFox和Jon Clements的麻烦。