[英]Selenium(PYTHON) check whether or not element exists
所以我試圖弄清楚如何正確運行這個循環,我的問題是,根據正在加載的鏈接,加載的頁面會有訪問被拒絕錯誤,這不是所有鏈接都這樣,我的問題是我想確定當特定元素加載到我的屏幕上時,程序是否識別它並中斷循環,並在 for 循環中開始下一次迭代,所以我試圖確定“拒絕訪問”元素是否存在,如果是則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")
請注意,如果顯示拒絕訪問頁面的元素不存在,我收到“拒絕訪問”元素不存在的錯誤,我該如何解決?
您想等待網頁收到正確的響應。 使用以下代碼,您可以等待加載的完整響應,然后根據結果采取適當的措施:
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")
...
因此,如果訪問被拒絕,那么您想循環訪問然后中斷。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.