AttributeError: 'NoneType' object has no attribute 'encode' while writing into file?

AttributeError: 'NoneType' object has no attribute 'encode' while writing into file?

我想抓取新内容并将其写入文件,但它给出 'NoneType' object has no attribute 'encode'

#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib2 as urllib
from bs4 import BeautifulSoup
import codecs
link = 'http://www.hindustantimes.com/delhi-news/delhi-man-shoots-    girlfriend-in-leg-after-argument-blames-snatchers/story-   CzA8JmgafX7tNUroilovoO.html'
reqlink = urllib.Request(link)
page = urllib.urlopen(reqlink)
soup = BeautifulSoup(page,'html.parser') 

fw = codecs.open('hlink7.txt','w')

var = soup.findAll('p')

for i in var:
      fw.write(i.string.encode('utf-8'))

如何解决?

如果您想对 p 标签的内容进行编码,那么您可能需要尝试使用 text 而不是 string.

像这样,

for i in var:
      fw.write(i.text.encode('utf-8'))

该异常表明您正在 None 对象上调用方法 encode。所以你应该先检查对象,然后再调用方法。像下面这样修改您的代码:

for i in var:
      if i.string:
            fw.write(i.string.encode('utf-8'))
if i is not None:

应该也可以:-)