0

我正在尝试解析一个表格,除了第 5 项之外没有任何问题。项目似乎有更精细的参数。

我有点困惑为什么会这样

我的代码是:

for row in tables.findAll('tr'):
    col = row.findAll('td')
    record =[]
    for i in range(0,9):
        cell = col[i].string.strip()

用“汤”:

<td align="left" class="table-top">Item1</td>
<td align="left" class="table-top">Item2</td>
<td align="left" class="table-top">Item3</td>
<td align="center" class="table-top">Item4</td>
<td align="right" class="table-top">Item5 <img align="top" alt="" border="0" height="12" src="gfx/chart_hover_icon.gif" width="15"/></td>

前 4 个被解析,但 5 个得到错误:

cell = col[i].string.strip()
AttributeError: 'NoneType' object has no attribute 'strip'
4

1 回答 1

1

文档

如果一个标签包含不止一个东西,那么不清楚 .string 应该指什么,所以 .string 被定义为 None

你的第五个td元素包含不止一个东西(一些文本和一个img),所以string属性是无。

您可以使用stringsorstripped_strings生成器来提取此内容 - 在这种情况下,您只有一个返回值,但值得考虑如何处理在之后还有文本的情况img

如果标签中包含多个内容,您仍然可以只查看字符串。使用 .strings 生成器

这些字符串往往有很多额外的空格,您可以使用 .stripped_strings 生成器来删除它们

或者,get_text将提取纯文本内容,并为您提供一些用于控制剥离和加入文本的选项。

于 2013-08-13T20:07:09.590 回答