[英]How to wait for the for loop to finish before next statement in Python (and Selenium)?
I have a list of 10 elements.我有一个包含 10 个元素的列表。 When I find a match in the list I want to click that element.
当我在列表中找到匹配项时,我想单击该元素。 If no element matches I want to go to the "next page".
如果没有元素匹配我想 go 到“下一页”。 (It is actually the same page but new async list elements is loaded in the list. Both lists has the same xpath.) Then I want to search the new page and click a element if it matches.
(实际上是同一个页面,但是列表中加载了新的异步列表元素。两个列表具有相同的 xpath。)然后我想搜索新页面并单击一个元素,如果它匹配。 Here is the code:
这是代码:
for xpath in list: # loop through elements
element = WebDriverWait(driver, 40).until(EC.presence_of_all_elements_located((By.XPATH, xpath)))
element = driver.find_element_by_xpath(xpath) # element fresh each time! no staleness here
match = re.search(patternForFindingListItem, element.text) #if match then click on the element/item
if match:
element.click()
break
if match == None: #want to go to next 10 items (notes) on "next page" (it is the same page but new loaded data via JavaScript) via next-button to see if there is a match there
elementButton = driver.find_element_by_xpath(xpathNextButton)
elementButton.click()
The problem is that it gets to the "next page" before the for loop is finished on the "first page".问题是它在 for 循环在“第一页”上完成之前到达“下一页”。 How can we wait for the loop to finish before going to the next page?
在进入下一页之前,我们如何等待循环完成?
There are several possible problems here:这里有几个可能的问题:
WebDriverWait(driver, 40).until(EC.presence_of_all_elements_located((By.XPATH, xpath)))
will not wait untill all the elements matching xpath
are presente. WebDriverWait(driver, 40).until(EC.presence_of_all_elements_located((By.XPATH, xpath)))
不会等到所有匹配xpath
的元素都出现。 It will return once at least one match found.element = driver.find_element_by_xpath(xpath)
according to the previous code line I guess you are trying to get the list of elements here, not a single element. element = driver.find_element_by_xpath(xpath)
根据前面的代码行我猜你想在这里获取元素列表,而不是单个元素。 If so you should use find_elements_by_xpath
here, so it will be elements = driver.find_elements_by_xpath(xpath)
find_elements_by_xpath
,所以它将是elements = driver.find_elements_by_xpath(xpath)
re.search(patternForFindingListItem, element.text)
...re.search(patternForFindingListItem, element.text)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.