use*_*195 12 python selenium try-except
我正在尝试在逐帧加载的网页上自动化流程.我正在尝试设置一个try-except循环,只有在确认元素存在后执行.这是我设置的代码:
from selenium.common.exceptions import NoSuchElementException
while True:
try:
link = driver.find_element_by_xpath(linkAddress)
except NoSuchElementException:
time.sleep(2)
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用,而以下天真的方法:
time.sleep(2)
link = driver.find_element_by_xpath(linkAddress)
Run Code Online (Sandbox Code Playgroud)
上面的try-except循环中是否有任何遗漏?我尝试了各种组合,包括使用time.sleep()之前try而不是之后except.
谢谢
neo*_*tic 26
您具体问题的答案是:
from selenium.common.exceptions import NoSuchElementException
link = None
while not link:
try:
link = driver.find_element_by_xpath(linkAddress)
except NoSuchElementException:
time.sleep(2)
Run Code Online (Sandbox Code Playgroud)
但是,有一种更好的方法可以等到元素出现在页面上:等待
另一种方式可能是。
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
try:
element = WebDriverWait(driver, 2).until(
EC.presence_of_element_located((By.XPATH, linkAddress))
)
except TimeoutException as ex:
print ex.message
Run Code Online (Sandbox Code Playgroud)
在 WebDriverWait 调用中,放置驱动程序变量和等待的秒数。
| 归档时间: |
|
| 查看次数: |
29909 次 |
| 最近记录: |