我的代码使用chromedriver扫描了很多互联网页面,并使用"find_elements_by_xpath“在每个页面中搜索相同的元素。
Lines = driver.find_elements_by_xpath(
'//*[@id="top"]/div[contains(@style, "display: block;")]/'
'div[contains(@style, "display: block;")]//tbody//a[contains(@title, "Line")]')
当它找到一个或多个时,它工作得又快又好。但是,当XPath不存在时,它会运行6-7秒,然后继续运行。
我可以将搜索限制为1秒,如果在1秒内找不到,就继续搜索吗?有没有办法做到这一点?
发布于 2017-08-10 01:28:38
尝试使用ExplicitWait,如下所示:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.common.exceptions import TimeoutException
try:
Lines = wait(driver, 1).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="top"]/div[contains(@style, "display: block;")]/'
'div[contains(@style, "display: block;")]//tbody//a[contains(@title, "Line")]')))
except TimeoutException:
pass
这应该允许您等待1秒,直到至少找到一个元素,然后获取所需的WebElements列表,否则什么也不做
https://stackoverflow.com/questions/45596974
复制相似问题