谢谢你的阅读!对于我的项目,我正在做的是滚动公司年度报告,以提取董事会成员和职位的姓名。因为不同的公司有不同的格式,所以我想尝试一种方法来获取信息,如果该过程导致“非类型”错误(因为一种方法找不到属性或关键字),请转到另一种方法并尝试该方法。我只需要一种方法来说明如果存在非类型错误,请尝试下一种方法。下面是导致错误的一种方法
tables_ticker = annual_report_page_soup.find(text="Age").find_parent("table")
resticker = []
for row in tables_ticker.find_all("tr")[1:]:
#print([cell.get_text(strip=True) for cell in row.find_all("td")])
if row:
resticker.append([cell.get_text(strip=True) for cell in row.find_all("td")])
non_empty_ticker = [sublist for sublist in resticker if any(sublist)]
df_ticker = pd.DataFrame.from_records(non_empty_ticker)
df_ticker[df_ticker == ''] = np.nan
df_ticker=df_ticker.dropna(axis=1, how='all')
print(df_ticker)
错误:
回溯(最近一次呼叫最后一次): 文件“C:/Users/james/PycharmProjects/untitled2/Edgar/WMT Working.py”,第84行,在 tables\u ticker=年度报告\u page\u soup.find(text=“Age”).find\u parent(“表格”) AttributeError:“非类型”对象没有“查找父对象”属性
下面是一个可以应用于代码的简单示例:
输出:
如您所见,一旦for循环到达列表中的第三项(不是字符串,而是
NoneType
对象),就会引发异常,因为NoneType
对象没有upper
方法。这在前两次迭代中有效,因为字符串确实有一个upper
方法解决方案-使用try-except块:
输出:
我们封装了一行代码,它可以抛出一个带有try-except块的潜在
AttributeError
。如果代码行引发这样一个异常,我们将使用continue
关键字跳过循环的这个迭代,并转到列表中的下一项同样,您可以封装此行:
tables_ticker = annual_report_page_soup.find(text="Age").find_parent("table")
用try-except块。但是,您可以切换刮片格式,而不是在循环中使用
continue
相关问题 更多 >
编程相关推荐