问题描述
我是使用Python的新手,并且正在尝试自动进行预订。
例如,我想今天预订下周。
这是网站上的代码:
<a href="#" class="dp-item" data-moment="October 29 2020" title="Thursday,29 October 2020" style="width: 113px;">
<div class="day row no-margin">
<div class="day-number col-xs-12">29</div>
</div>
<div class="day-week">Thursday</div>
<div class="month">October</div>
</a>
并在我的代码下方:
-
我尝试指定一个日期,以检查日期是否有效但没有运气:
driver.find_element_by_xpath("//a[@title='Thursday,29 October 2020']").click()
-
最后,我要实现的是使用这样的变量:
today = datetime.datetime.now() nextweek = today + datetime.timedelta(days=7) driver.find_element_by_xpath("//a[@title='nextweek.strftime(%A %d %B %Y']").click()
解决方法
我认为更好的方法是
driver.find_element_by_link_text('nextweek.strftime(%A %d %B %Y').click()
代码如下
today = datetime.datetime.now() nextweek = today + datetime.timedelta(days=7)
driver.find_element_by_link_text('nextweek.strftime(%A %d %B %Y').click()
它将找到类“ dp-item”,在这种情况下,我认为它更好 (我没有测试此代码。如果您遇到任何错误,请告诉我)
,在Python 3.8及更高版本中尝试f-string,这是上帝的发送。 Docs
import datetime
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# assuming you have `driver` here
# driver = ...
today = datetime.datetime.now()
nextweek = datetime.timedelta(weeks=1) + today
nextweek_formatted = nextweek.strftime("%B %d %Y")
xpath = f'//a[@data-moment="{nextweek_formatted}"]'
# now getting <a> tag
link = WebDriverWait(driver,10).until(EC.element_to_be_clickable(By.XPATH,xpath))
link.click()
优良作法是使用WebDriverWait
查找元素。
- 如果正常找到该页面,则该页面可能没有足够的时间将元素加载到DOM中,可能会导致错误的问题(
NoSuchElement
异常,即使加载元素只需要1-2秒)。 - 使用
EC.element_to_be_clickable
来真正等待元素被单击,因为您以后需要单击它。
另外,请实现try
except
,如果driver
找不到元素,它将引发TimeoutException
。我没有在示例代码中实现它,但是您可以尝试:)。