[英]How to click on the input element with value as Download Catalogues using Selenium and Python
[英]How to click on an input element using Selenium and Python
我正在嘗試單擊Selenium 文檔網站中文本為Python
的選項卡。
HTML:
<input type="radio" name="tabsetcode2" id="tab1code2" aria-controls="pythoncode2">
但我面臨TimeoutException
:
selenium.common.exceptions.TimeoutException: Message:
代碼試驗:
driver.get('https://www.selenium.dev/documentation/en/')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[aria-controls='pythoncode2']"))).click()
誰能幫我點擊Python
選項卡?
嘗試通過 xpath 等待
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, '*//div[@class="tabset"]/label[2]'))).click()
如果仍然不起作用,請嘗試等待直到可見
WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.XPATH, '*//div[@class="tabset"]/label[2]'))).click()
首先,優先使用 Id > Css 選擇器 > XPaths。 所以示例代碼可能是(By.CSS_SELECTOR, "#pythoncode2")
或更好(By.ID, "pythoncode2")
。
但是,無論如何,這不是一個可點擊的元素,因此盡管等待 20 秒,它總是會達到超時等待它變為“可點擊”。 (如果您通過 F12 和 select 該選項卡在瀏覽器上 go 進入“開發人員模式”,則單選按鈕的圓圈具有left -1704px
的樣式,該選項不在屏幕上。驅動程序認為其視口之外的任何內容都是不可點擊的)
可點擊元素為目標label; 沒有Id,但是可以通過CSS找到它: (By.CSS_SELECTOR, "label[for=tab1code2]")
這是我的工作代碼來證明它有效:
from selenium import webdriver
if __name__ == '__main__':
driver = webdriver.Chrome("./chromedriver")
driver.get('https://www.selenium.dev/documentation/en/')
driver.find_element_by_css_selector("label[for=tab1code2]").click()
您可以改為單擊 label 並且它可以工作。
driver.get('https://www.selenium.dev/documentation/en/')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='tab1code2']"))).click()
該元素確實是可點擊的。 但它與 label 標簽綁定。
有關更多信息,關於綁定 label 和信息在這里
使用EC.element_to_be_clickable
還可以確保元素可見,但事實並非如此。
class element_to_be_clickable(object):
""" An Expectation for checking an element is visible and enabled such that
you can click it."""
您可以通過調用is_enabled
來確認它是可點擊的。 此方法僅驗證disabled
屬性是否為 false。
driver.find_element_by_css_selector("input[aria-controls='pythoncode2']").is_enabled()
或者
driver.find_element_by_css_selector("input[aria-controls='pythoncode2']").get_attribute('disabled') != "true"
結果:
True
但是EC.element_to_be_clickable
也調用is_displayed
來確定元素是否也可見
driver.find_element_by_css_selector("input[aria-controls='pythoncode2']").is_displayed()
結果:
False
這就是為什么,無論你等待多久,它永遠不會成為現實。
要單擊輸入元素,您可以改為定位 label 元素。 它們與屬性for=id
綁定在一起
在你的情況下
driver.find_element_by_css_selector('[for="tab1code2"]')
還:
driver.find_element_by_css_selector('[for="tab1code2"]').is_enabled()
driver.find_element_by_css_selector('[for="tab1code2"]').is_displayed()
兩者都返回: True
如果您嘗試使用您選擇的 css 選擇器單擊元素,則會引發以下異常:
ElementNotInteractableException: Message: element not interactable"
原因在於type="radio"
屬性。
相反,您應該嘗試使用以下 css 選擇器單擊下方的 label 元素:
("label[for=tab1code2]")
因此,您的代碼應如下所示:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label[for=tab1code2]"))).click()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.