python错误消息-元素不可见

时间:2019-07-09 09:32:14

标签: python-3.x selenium xpath css-selectors webdriverwait

我收到此错误:

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")

问题2: 单击红色按钮后,如何在带有python硒的弹出窗口中的按钮上获取元素?

元素: button type =“ 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

2 个答案:

答案 0 :(得分:0)

您可以使用显式等待代替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)))

答案 1 :(得分:0)

要在所需元素内发送字符序列,您必须为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
    
  • 浏览器快照:

YOYO