如果发生异常,如何重新启动 try 循环

时间:2021-07-28 13:31:23

标签: python selenium loops try-catch

我正在编写一个 webscraper,它使用来自现有电子表格的数据从网站中提取数据。它使用某个列中的代码(即参考产品)来搜索站点。但是,当搜索一个产品时,会显示多个,只有一个是正确匹配的。我创建了一个系统,可以搜索正确的代码并通过 find_element_by_xpath 选择产品,但它不考虑多个页面。我的目标是(在找不到代码的情况下)移动到下一页并搜索相同的代码而不移动到下一个 excel 行,在到达最后一页时停止。我已经找到了一段可以移到下一页的代码:

try:
    _driver.find_element_by_class_name("next").click()
    print("Navigating to Next Page")
except TimeoutException as e:
    print("Final Page")
    break

但是,我不确定在不破坏代码或向下移动的情况下我将在哪里/如何实现它。 这是迄今为止我的代码工作方式的片段(显然已简化)

for i in data.index: #(_data is spreadsheet column)
    try:
        # locate product code
        # copy product link
        # navigate to link

        try:
        # wait for site to load 

        # Copy data to Spreadsheet 

        except TimeoutException:
        # Skip if site takes too long

     except Exception as e:
     # Catch any possible exceptions and continues loop (normally when product cannot be found)

任何帮助都将不胜感激,无论是如何实现上面的代码片段,还是从页面移动到页面的更好方法。如果需要,我可以提供更详细的网站链接或代码片段:)

2 个答案:

答案 0 :(得分:0)

Python 程序在遇到错误时立即终止。在 Python 中,错误可以是语法错误或异常。 try-except 代码可让您测试代码并捕获可能发生的异常,而无需终止程序。

对于您的问题,您可能需要使用 recursion functions 来浏览页面。

你可以试试这样的:

def rec(site, product):
    if(final-page)
        return exception_not_found

    try:
        # locate product code

        try:
        # wait for site to load 
        # Copy data to Spreadsheet 
        if(found_product)
            return #found, break

        except TimeoutException:
        return # Skip if site takes too long
    except Exception as e:
        return # Skip if fails ? 

    if(we_did_not_find_product)
        # copy product link
        # navigate to link
        #navigate to next site
        rec(next_site, product)


for i in data.index: #(_data is spreadsheet column)
    rec(init_side, i)

对于电子表格中的每一行,我们进入初始页面,查找产品,如果没有找到,则移至下一页,直到找到产品或到达最后一页。下一行的情况:如果出现异常,找到产品,到达下一页。

答案 1 :(得分:0)

我是怎么做的(将页面移动器和代码检查器存储为函数并使用它们相互调用):

def page_mover():
    try:
        # Click Next page
        page_link()
    except Exception:
        print("Last page reached")

def page_link():
    try:
        # Wait for page to load
        # Get link using product code
        # Go to link
    except Exception:
        page_mover()
相关问题