Webscraping在“非类型”对象没有属性时添加If语句

2024-09-30 20:25:20 发布

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

谢谢你的阅读!对于我的项目,我正在做的是滚动公司年度报告,以提取董事会成员和职位的姓名。因为不同的公司有不同的格式,所以我想尝试一种方法来获取信息,如果该过程导致“非类型”错误(因为一种方法找不到属性或关键字),请转到另一种方法并尝试该方法。我只需要一种方法来说明如果存在非类型错误,请尝试下一种方法。下面是导致错误的一种方法

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:“非类型”对象没有“查找父对象”属性


Tags: 方法textin类型dffortables错误
1条回答
网友
1楼 · 发布于 2024-09-30 20:25:20

下面是一个可以应用于代码的简单示例:

for item in ["Hello", "World", None, "Foo", None, "Bar"]:
    print(item.upper())

输出:

HELLO
WORLD
Traceback (most recent call last):
AttributeError: 'NoneType' object has no attribute 'upper'
>>> 

如您所见,一旦for循环到达列表中的第三项(不是字符串,而是NoneType对象),就会引发异常,因为NoneType对象没有upper方法。这在前两次迭代中有效,因为字符串确实有一个upper方法

解决方案-使用try-except块:

for item in ["Hello", "World", None, "Foo", None, "Bar"]:
    try:
        print(item.upper())
    except AttributeError:
        continue

输出:

HELLO
WORLD
FOO
BAR
>>> 

我们封装了一行代码,它可以抛出一个带有try-except块的潜在AttributeError。如果代码行引发这样一个异常,我们将使用continue关键字跳过循环的这个迭代,并转到列表中的下一项

同样,您可以封装此行:

tables_ticker = annual_report_page_soup.find(text="Age").find_parent("table")

用try-except块。但是,您可以切换刮片格式,而不是在循环中使用continue

相关问题 更多 >