Issue
I want to scrape new content and write it into a file but it is giving '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'))
how to resolve it?
Solution
The exception indicates that you are invoking a method encode
on an object which is None
. So you should check the object first, before invoking the method. Modify your code like the following:
for i in var:
if i.string:
fw.write(i.string.encode('utf-8'))
Answered By - mshsayem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.