我正在撰寫一個程式來使用 chromedriver 在我的圖書館中自動預訂一張桌子。我正在遍歷所有座位,尋找尚未預訂的座位,然后使用
driver.find_element(By.XPATH, xpath).click()
在開始和結束時間預訂座位。點擊后,可能會彈出不同的警報,確認預訂或指出問題。這些警報會在幾秒鐘后消失。我正在嘗試使用彈出視窗的文本來驗證預訂是否成功。
到目前為止,我已經嘗試過:
try:
WebDriverWait(driver, 10).until(EC.alert_is_present)
alert = driver.switch_to.alert
text = alert.text
if "some Text" in text:
print("Booking successful")
elif "some other text" in text:
print("booking not successful")
except:
print("no alert")
但是,警報沒有被識別,我總是得到“沒有警報”。
這是警報的樣子:
<div data-notify="container" class="col-xs-11 col-sm-4 alert alert-success animated fadeInDown" role="alert" data-notify-position="top-center" style="display: inline-block; margin: 0px auto; position: fixed; transition: all 0.5s ease-in-out 0s; z-index: 5000; top: 20px; left: 0px; right: 0px;">
<button type="button" aria-hidden="true" class="close" data-notify="dismiss" style="position: absolute; right: 10px; top: 5px; z-index: 5002;"> × </button>
<span data-notify="icon"> </span>
<span data-notify="title"></span>
<span data-notify="message"> Booking successful. </span>
<a href="#" target="_blank" data-notify="url"> </a>
</div>
uj5u.com熱心網友回復:
由于存在 , 等類名,WebElement看起來像一個警報。但它不是一個實際的警報alertalert-success
列印文本預訂成功。從警報中,您可以使用以下任一定位器策略:
使用css_selector和
get_attribute("innerHTML"):print(driver.find_element(By.CSS_SELECTOR, "div[class*='alert'][data-notify='container'] span[data-notify='message']").get_attribute("innerHTML"))使用xpath和text屬性:
print(driver.find_element(By.XPATH, "//div[contains(@class, 'alert') and @data-notify='container']//span[@data-notify='message']").text)
理想情況下,您需要為visibility_of_element_located()引入WebDriverWait ,并且您可以使用以下任一Locator Strategies:
使用CSS_SELECTOR和text屬性:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div[class*='alert'][data-notify='container'] span[data-notify='message']"))).text)使用XPATH和
get_attribute("innerHTML"):print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class, 'alert') and @data-notify='container']//span[@data-notify='message']"))).get_attribute("innerHTML"))注意:您必須添加以下匯入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在如何使用 Selenium - Python 檢索 WebElement 的文本中找到相關討論
參考
鏈接到有用的檔案:
get_attribute()方法Gets the given attribute or property of the element.text屬性回傳The text of the element.- 使用 Selenium 的 text 和 innerHTML 之間的區別
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417973.html
標籤:
上一篇:按下按鈕將影像添加到幀
