我遇到了一个递归错误[RuntimeError:调用Python对象时超过了最大递归深度],但我的代码是迭代的还是它?

2024-06-06 07:53:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到一个递归错误:

RuntimeError: maximum recursion depth exceeded while calling a Python object

但我的代码是迭代的…还是这样?我认为是的,基于文档(这里,例如:http://www.pythonlearn.com/html-008/cfbook006.html)。{我不知道递归算法是如何改变的。在

这段代码进入一个网站,进行搜索并返回大约122页的结果。然后单击每个结果页面并收集链接。然后单击每个链接并从每个链接中获取text/html。在

代码运行得很好,直到到达最后一个for循环:for url in article_urls:。在返回错误之前,它将捕获并存储(在dropbox上)200多个shtml页面。在

我想解决的难题是:如何避免出现这种错误?在

代码如下:



from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

def isReady(browser):
    return browser.execute_script("return document.readyState") == "complete"

def waitUntilReady(browser):
    if not isReady(browser):
        waitUntilReady(browser)

browser = webdriver.Firefox()
browser.get('http://www.usprwire.com/cgi-bin/news/search.cgi')

# make a search
query = WebDriverWait(browser, 60).until(EC.presence_of_element_located((By.NAME, "query")))
query.send_keys('"test"')
submit = browser.find_element_by_xpath("//input[@value='Search']")
submit.click()
numarticles = 0

# grab article urls
npages = 1
article_urls = []
for page in range(1, npages + 1):
    article_urls += [elm.get_attribute("href") for elm in browser.find_elements_by_class_name('category_links')]
    if page <= 121: #click to the next page
        browser.find_element_by_link_text('[>>]').click()
    if page == 122: #last page in search results, so no '[>>]'' to click on. Move on to next steps.
        continue



# iterate over urls and save the HTML source
for url in article_urls:
    browser.get(url)
    waitUntilReady(browser)
    numarticles = numarticles+1
    title = browser.current_url.split("/")[-1]
    with open('/Users/My/Dropbox/File/Place/'+str(numarticles)+str(title), 'w') as fw:
        fw.write(browser.page_source.encode('utf-8'))

非常感谢您的任何意见。在


Tags: infromimportbrowserurlforbyselenium
2条回答

waitUntilReady是一个递归函数!它可能会被多次调用,特别是当你的连接速度很慢时。在

以下是一个可能的解决方法:

def waitUntilReady():
    while not isReady():
        time.sleep(10)

显然,您的waitUntilReady进入无限递归,调用自己。在

你应该改成这样:

while not isReady(browser):
    time.sleep(1)

等待页面完全加载到Selenium中并不像看上去那么明显,您可以在Harry J.W. Percival's article中阅读更多内容

相关问题 更多 >