【问题标题】:Selenium(PYTHON) check whether or not element existsSelenium(PYTHON) 检查元素是否存在
【发布时间】:2021-05-17 09:45:09
【问题描述】:

所以我试图弄清楚如何正确运行这个循环,我的问题是,根据正在加载的链接,加载的页面将有一个访问被拒绝错误,这不是所有链接都这样,我的问题是我想确定当特定元素加载到我的屏幕上时,程序是否识别它并中断循环,并在 for 循环中开始下一次迭代,所以我试图确定“访问被拒绝” element 存在,如果存在则break,否则继续for循环

idList = ["8573", "85678", "2378", "2579"]


for ID in idList:


    print(ID)
    driver.get(f"https://www.someWebsite/username/{ID}")

    element = driver.find_element_by_class_name("Access-Denied")
   
    print("error loading website")
    break
if not element:

    print("you may continue the for loop")

请注意,如果显示拒绝访问页面的元素不存在,我收到“拒绝访问”元素不存在的错误,我该如何解决?

【问题讨论】:

    标签: python html selenium webautomation


    【解决方案1】:

    因此,如果访问被拒绝,那么您想循环遍历然后中断。

    wait = WebDriverWait(driver, 10)
    idList = ["8573", "85678", "2378", "2579"]
    
    for ID in idList:
        print(ID)
        driver.get(f"https://www.someWebsite/username/{ID}")
        try:
            element=wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'Access-Denied')))
            break
        except:
            continue
    

    导入

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

    【讨论】:

      【解决方案2】:

      您希望等待网页收到正确的响应。使用下面的代码,你可以等待完整的响应加载,然后取 根据结果​​采取适当的行动:

      from selenium.webdriver.common.by import By
      from selenium.common.exceptions import TimeoutException
      from selenium.webdriver.support.ui import WebDriverWait
      
      ...
      try:
          _ = WebDriverWait(driver, 10).until(
                  EC.presence_of_element_located((By.CLASS_NAME, "Access-Denied"))
              )
          print("error loading website")
          break
      except TimeoutException:
          print("you may continue the for loop")
      ...
      
      

      【讨论】:

        猜你喜欢
        • 2018-01-23
        • 1970-01-01
        • 2012-03-22
        • 1970-01-01
        • 2016-08-05
        • 2021-07-08
        • 1970-01-01
        • 1970-01-01
        • 2022-10-20
        相关资源
        最近更新 更多