【问题标题】:Can't create a function expected to be called in the end of an execution无法创建预期在执行结束时调用的函数
【发布时间】:2020-11-24 05:57:10
【问题描述】:

我试图弄清楚是否可以创建一个在执行结束时调用的函数,无论其他函数是否遇到任何错误。更具体地说 - 在以下示例中有一个函数bound_to_call(),一旦执行完成或中断,需要自动调用该函数。在scrapy def close(spider, reason) 中有一个方法正是我试图描述的。

我想使用此函数 bound_to_call() 保存 Excel 工作簿,因为当调用此行 wb.save('SO.xlsx') 时工作簿就存在了。但是,通常最后会调用该行,如果不调用,即使脚本抓取了大部分结果,也不会有工作簿。

import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook

link = "https://stackoverflow.com/questions/tagged/web-scraping"

def get_info(s,link):
    r = s.get(link)
    soup = BeautifulSoup(r.text,"lxml")
    for item in soup.select(".summary"):
        user = item.select_one(".user-details > a").get_text(strip=True)
        title = item.select_one(".question-hyperlink").get_text(strip=True)
        ws.append([user,title])
        print(user,title)

def bound_to_call():
    wb.save('SO.xlsx')

if __name__ == "__main__":
    wb = Workbook()
    wb.remove(wb['Sheet'])
    ws = wb.create_sheet('useractivity')
    ws.append(['name','title'])
    with requests.Session() as s:
        get_info(s,link)
    bound_to_call()

问题:如何在执行结束时调用函数,不管是否有错误?

【问题讨论】:

    标签: python python-3.x function web-scraping


    【解决方案1】:

    使用 python Exception 表单来捕获错误,即。 try:except: 这是带有异常处理的代码(py3):

    if __name__ == "__main__":
        try:
            wb = Workbook()
        except Exception as err:
            print("Error on creating workbook", err)
            exit()
    
        try:
            wb.remove(wb['Sheet'])
            ws = wb.create_sheet('useractivity')
            ws.append(['name','title'])
            with requests.Session() as s:
                get_info(s,link)
        except Exception as err:
            print("Error scraping website", err)
    
        # This will be called so long as wb is instanciated. 
        bound_to_call()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 2018-04-08
      • 2021-03-20
      • 2017-07-08
      • 1970-01-01
      相关资源
      最近更新 更多