Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

'NoneType' object has no attribute 'strip'?

html是这样的:

<td class="cell_43 cell_guaranteed">
                '5 - 7'
      ::after    
    </td>

<td class="cell_44">
      ::after
    </td>

<td class="cell_45">
      ::after
    </td>

运行以下程序:

info_list = []
table = tree.xpath('//table[@class="market_table_content"]')[0] 
for tr in table.xpath('.//tr[not(@class)]'):
                     
    info = {
                '选择': tr.xpath('.//td[@class="cell_43 cell_guaranteed"]')[0].text.strip(' 
 '),
                '数字': tr.xpath('.//td[@class="cell_44"]')[0].text.strip(' 
 '),
                '产量': tr.xpath('.//td[@class="cell_45"]')[0].text.strip(' 
 '),
                '订单量': eval(tr.xpath('.//div[@class="btn_order"]/button')[0].get('onclick').strip('MarketOrder'))
            } 
            info_list.append(info)

运行时,由于html中cell_44、cell_45中是空值,程序返回以下错误:

AttributeError: 'NoneType' object has no attribute 'strip'

请各位大佬帮助以上问题该如何解决?请回复详细代码,谢谢。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

先对获取到的内容进行判断,如果为Nonetype是无法使用strip进行切分的

info_list = []
table = tree.xpath('//table[@class="market_table_content"]')[0] 
for tr in table.xpath('.//tr[not(@class)]'):
    # 处理数量
    number_text = tr.xpath('.//td[@class="cell_44"]')[0].text
    number = number_text.strip(' rn ') if number_text else []
    # 处理产量, 选择,订单量同样的逻辑进行处理

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...