我正在試驗一些網路測驗自動化。
為了練習,我使用了Sause 演示站點
它在頁面
<input type="submit" data-test="login-button" id="login-button" name="login-button" value="Login">
上定義了登錄按鈕,因為它在螢屏上的文本是“登錄”(大寫)。
我想從登錄按鈕獲取文本。
首先,我只是嘗試使用login_button.text它并回傳空字串。好的,很明顯原因和預期。
然后我嘗試獲取 login_button 的屬性值,它回傳“登錄”字串。
我檢查了登錄按鈕是否應用了以下 CSS 樣式并使文本大寫。
.submit-button {
text-transform: uppercase;
}
但是有沒有可能從此按鈕獲取文本的確切顯示方式(“登錄”而不是“登錄”)?
我使用的代碼示例:
driver = webdriver.Chrome(CHROME_DRIVER_PATH)
driver.get("https://www.saucedemo.com/")
login_button = driver.find_element_by_id("login-button")
print(login_button.text) # returns empty string
print(login_button.get_property("value")) # returns "Login"
driver.quit()
uj5u.com熱心網友回復:
直接的答案是 Seleniuman HTTP 向 DOM發出請求,它可以update/retrieve info from DOM.
在您的情況下,正如您所強調的那樣,是一個 CSS 屬性(文本轉換)進行了此更改。
您可以閱讀此屬性,并根據資訊制作 Pythonupper()或lower()
我建議從CSS property和使用進行驗證
driver.get("https://www.saucedemo.com/")
login_button = driver.find_element_by_id("login-button")
actual_login_button_text = login_button.get_attribute('value')
print('Actual text', actual_login_button_text)
text_type = login_button.value_of_css_property('text-transform')
print('CSS text type', text_type)
change_text = ''
if text_type == 'uppercase':
change_text = actual_login_button_text.upper()
if text_type == 'lowercase':
change_text = actual_login_button_text.lower()
print('Modified text', change_text)
輸出 :
Actual text Login
CSS text type uppercase
Modified text LOGIN
uj5u.com熱心網友回復:
Selenium 讀取HTML DOM,但不會讀取螢屏上顯示的內容。
該LOGIN按鈕實際上有一個屬性的值設定為Login
要提取value屬性值,您可以使用以下任一定位器策略:
使用
CSS_SELECTOR:print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input#login-button"))).get_attribute("value"))使用
XPATH:print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//input[@id='login-button']"))).get_attribute("value"))控制臺輸出:
Login注意:您必須添加以下匯入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
正如您正確指出的,值Login應用了以下 CSS 樣式:
text-transform: uppercase;
將其以大寫形式呈現為LOGIN。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/351360.html
標籤:硒 硒网络驱动程序 html-输入 网络自动化 提交按钮
