簡體   English   中英

python-如果此迭代花費的時間太長,則繼續循環

[英]python - continue the loop if this iteration takes too long time

我的PhantomJS有問題,它可以掛在循環中而不會報告任何錯誤。 我知道我的代碼很好,因為重新啟動后,它通常會完成,並且可能稍后會掛起。 我想到的可能是這樣的:

i = 0
while i < len(url_list):
    try:
        driver.get(url_list[i])
        # do whatever needs to be done
        i = i+1
        # go on the next one
    except ThisIterationTakesTooLong:
        # try again for this one because the code is definitely good
        continue

甚至可以做這樣的事情嗎? 基本上,這是后台檢查循環運行多長時間的一件事。 我知道time.time(),但問題是它甚至無法測量它是否掛在計數器之前的命令上。


編輯
看完建議的問題后,我仍然遇到問題,因為該信號模塊無法正常工作。

import signal
signal.alarm(5)

這將引發“ AttributeError:'模塊'對象沒有屬性'警報'”
所以看起來我真的不能使用它。

之前我已經遇到過這種事情,但是不幸的是,目前還沒有解決的辦法。 事實是,有時頁面/元素只會加載,而您必須對此做出選擇。 我通常會做這樣的事情:

from selenium.common.exceptions import TimeoutException

# How long to wait for page before timeout
driver.set_page_load_timeout(10)

def wait_for_url(driver, url, max_attempts):
    """Make multiple attempts to load page
    according to page load timeout, and
    max_attempts."""

    attempts = 0

    while attempts < max_attempts:

        try:
            driver.get(url)
            return True

        except TimeoutException:
            # Prepare for another attempt
            attempts += 1

            if attempts == 10:
                # Bail on max_attempts
                return False

# We'll use this if we find any urls that won't load
# so we can process later. 
revisit = []

for url in url_list:

    # Make 10 attempts before giving up.
    url_is_loaded = wait_for_url(driver, url, 10)

    if url_is_loaded:
        # Do whatever

    else:
        revisit.append(url)

# Now we can try to process those unvisitied URLs. 

我還要補充一點,問題可能出在PhantomJS。 硒的最新版本已棄用。 以我的經驗,PhantomJS呆滯並且容易發生意外行為。 如果您無頭,可以使用非常穩定的Chrome。 如果您不熟悉,則如下所示:

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")

driver = webdriver.Chrome(path/to/chromedriver, chrome_options=chrome_options)

這些建議之一可能會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM