【问题标题】:Python Selenium Click on a titlePython Selenium 点击一个标题
【发布时间】:2020-10-22 05:58:07
【问题描述】:

我是 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()
    

【问题讨论】:

    标签: python selenium xpath click title


    【解决方案1】:

    我认为更好的方法是

    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”,我认为在这种情况下它会更好 (我没有测试这个代码。如果你有任何错误,请告诉我)

    【讨论】:

    • 谢谢!我在几次测试中也测试了该代码,但我得到了这个:selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: nextweek.strftime(%A %d %B %Y)
    • 如果没有其他标签具有相同的类名,您可以使用driver.find_element_by_css_selector('.dp-item')driver.find_element_by_class_name('db-item'),如果该类重复两次或多次,您可以使用与用f编写的相同的代码- 字符串方法driver.find_element_by_xpath(f"//a[@title='{day}, {date} {month} {year} ']")
    【解决方案2】:

    在 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 真正等待元素可点击,因为您需要稍后点击它。

    另外,请实现tryexcept,如果driver找不到元素,则会引发TimeoutException。我没有在示例代码中实现它,但你可以尝试:)。

    【讨论】:

    • 谢谢。确切地说,我得到了一个 TimeoutException。但我不确定我是否理解。为什么我应该使用 try except,我的意思是如果我不能点击那个元素,我就不能进行预订。
    • TimeoutException 用于找不到元素的情况。在这种情况下,例如,您找不到“2020 年 10 月 29 日”的按钮。如果你找不到它,你应该处理它。如果您的网站只有一个月可用,而您的下周是 11 月,您需要点击“下个月”元素,然后找到日期。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2016-08-11
    • 1970-01-01
    相关资源
    最近更新 更多