如何根据定义的变量更改xpath

时间:2020-10-26 07:39:42

标签: python selenium xpath

希望你一切都好。

有一个站点,下拉框的xpath名称每天都会更改(即,今天的下拉框名为“ 2020-10-26timeWindows”,明天将更改为“ 2020-10-27timeWindows”)。

我可以使用datetime动态更改下拉名称。但是,我还需要从下拉框中选择值。如果您可以帮助研究以下代码并告诉我是否有必要在下拉列表中使用“今天”,我们将不胜感激。

today = str(datetime.today().strftime("%Y-%m-%d"))
dropdown = driver.find_element(By.ID,  "{}timeWindows".format(today))
time.sleep(0.2)       
dropdown.find_element_by_xpath("//select[@id=\'2020-10-26timeWindows\']/option[. = '19:30 – 19:45']").click()

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我将使用以下格式字符串:

today = str(datetime.today().strftime("%Y-%m-%d"))
t = "{}timeWindows".format(today)
dropdown = driver.find_element(By.ID, t)
time.sleep(0.2)       
dropdown.find_element_by_xpath("//select[@id=\'{}\']/option[. = '19:30 – 19:45']".format(t)).click()

答案 1 :(得分:0)

  • 您可以使用此修改使其动态化
today = datetime.datetime.now().date()
  • 编辑您的代码
today = str(datetime.datetime.now().date())
dropdown = driver.find_element(By.ID,  "{}timeWindows".format(today))
time.sleep(0.2)       
dropdown.find_element_by_xpath("//select[@id=\'2020-10-26timeWindows\']/option[. = '19:30 – 19:45']").click()

Documentation获得更多帮助