' NoneType' object不可调用:BeautifulSoup HTML解析

时间:2015-04-24 16:20:07

标签: python html parsing csv beautifulsoup

我正在尝试解析网页中的HTML表格,我将其作为字符串输入传递给BeautifulSoup。我已经给出了以下脚本来解析HTML页面并将内容打印在CSV文件中:

soup = BeautifulSoup(In_put)
comments = soup.find_all('td', {"id": "TicketDetails_TicketDetail_TicketDetail__ctl0_Tablecell1"})
f = open(Out_put, 'w')
writer = csv.writer(f)
for s in comments:
    writer.writerow(s.split('##'))
f.close()

但它显示错误说:

Traceback (most recent call last):
  File "C:/Users/KOS974/PycharmProjects/test_cases/gasper_try.py", line 561, in <module>
    writer.writerow(s.split('##'))
TypeError: 'NoneType' object is not callable

即使<tr>标记中的某些内容具有相同的id,我也无法理解错误发生的原因。

1 个答案:

答案 0 :(得分:2)

您正尝试在BeautifulSoup .split()个实例上调用方法Element

此类对象没有 .split()方法,但他们会尝试搜索他们无法识别的任何属性。 element.split已转换为element.find('split'),但找不到<split>代码,并且会返回None。由于您使用的是element.split(),因此最终会使用None(),但这会失败。

您想首先从每个元素中提取文本

for s in comments:
    writer.writerow(s.get_text().split('##'))