簡體   English   中英

Python Selenium 點擊標題

[英]Python Selenium Click on a title

我是 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,它是上帝發送的。 文檔

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 我沒有在示例代碼中實現它,但您可以嘗試:)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM