python 错误消息 - 元素不可见

python error message - Element not visible

我收到这个错误:

selenium.common.exceptions.ElementNotVisibleException: Message: element not visible. or Element is not currently interactable.

我该如何解决?

元素:

input class="artfld col-all-min ng-pristine ng-invalid ng-touched" formcontrolname="id" maxlength="10" placeholder="身分證字號" type="text"

代码:

from selenium import webdriver
import time
from PIL import Image
from pynput.keyboard import Key,Controller
browser = webdriver.Chrome()
browser.get('https://mma.sinopac.com/SinoCard/Activity/Register?Code=TLDI')
time.sleep(0.3)
browser.find_element_by_xpath("/html/body/app-root/div/app-activity-register/div/div[2]/div/div/section/app-activity-register-verification/form/div[1]/table/tbody/tr[3]/td/input").send_keys("1234")

问题二: 单击红色按钮后,如何使用 python selenium 在弹出窗口 window 中获取按钮上的元素?

元素: 按钮类型="button" class="swal2-confirm swal2-styled" aria-label="" style="background-color: rgb(48, 133, 214); border-left-color: rgb(48, 133, 214); border-right-color: rgb(48, 133, 214);">确定/button

您可以使用显式等待而不是 time.sleep(0.3),如下所示:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Chrome()

# wait for an element to appear.
wait = WebDriverWait(browser, 10)
waited_element = wait.until(EC.visibility_of_element_located((By.XPATH, xpath_of_element)))

要在所需元素内发送 字符序列,您必须为 element_to_be_clickable() 引入 WebDriverWait 并且您可以使用以下任一解决方案:

  • 使用CSS_SELECTOR:

    driver.get("https://mma.sinopac.com/SinoCard/Activity/Register?Code=TLDI")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.artfld.col-all-min.ng-untouched.ng-pristine.ng-invalid[formcontrolname='id']"))).send_keys("YOYO")
    
  • 使用XPATH:

    driver.get("https://mma.sinopac.com/SinoCard/Activity/Register?Code=TLDI")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='artfld col-all-min ng-untouched ng-pristine ng-invalid' and @formcontrolname='id']"))).send_keys("YOYO")
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
  • 浏览器快照: