Python Selenium Webdriver - 尝试除了循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22741591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Selenium Webdriver - Try except loop
提问by user3294195
I'm trying to automate processes on a webpage that loads frame by frame. I'm trying to set up a try-except
loop which executes only after an element is confirmed present. This is the code I've set up:
我正在尝试在逐帧加载的网页上自动执行流程。我正在尝试设置一个try-except
循环,该循环仅在确认存在元素后才执行。这是我设置的代码:
from selenium.common.exceptions import NoSuchElementException
while True:
try:
link = driver.find_element_by_xpath(linkAddress)
except NoSuchElementException:
time.sleep(2)
The above code does not work, while the following naive approach does:
上面的代码不起作用,而以下幼稚的方法却起作用:
time.sleep(2)
link = driver.find_element_by_xpath(linkAddress)
Is there anything missing in the above try-except loop? I've tried various combinations, including using time.sleep() before try
rather than after except
.
上面的 try-except 循环中是否缺少任何内容?我尝试了各种组合,包括使用 time.sleep() beforetry
而不是 after except
。
Thanks
谢谢
采纳答案by neoascetic
The answer on your specific question is:
您的具体问题的答案是:
from selenium.common.exceptions import NoSuchElementException
link = None
while not link:
try:
link = driver.find_element_by_xpath(linkAddress)
except NoSuchElementException:
time.sleep(2)
However, there is a better way to wait until element appears on a page: waits
但是,有一个更好的方法来等待元素出现在页面上:waits
回答by Charls
Another way could be.
另一种方式可能是。
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
Inside the WebDriverWait call, put the driver variable and seconds to wait.
在 WebDriverWait 调用中,放置驱动程序变量和等待的秒数。