Python 使用BeautifulSoup从HTML页面获取内容类型
我正在尝试为我刮取的页面获取字符编码,但在某些情况下失败了。以下是我正在做的:Python 使用BeautifulSoup从HTML页面获取内容类型,python,lambda,beautifulsoup,Python,Lambda,Beautifulsoup,我正在尝试为我刮取的页面获取字符编码,但在某些情况下失败了。以下是我正在做的: resp = urllib2.urlopen(request) self.COOKIE_JAR.extract_cookies(resp, request) content = resp.read() encodeType= resp.headers.getparam('charset') resp.close() 这是我第一次尝试。但如果字符集返回为typeNone,我会这样做: soup = Beautiful
resp = urllib2.urlopen(request)
self.COOKIE_JAR.extract_cookies(resp, request)
content = resp.read()
encodeType= resp.headers.getparam('charset')
resp.close()
这是我第一次尝试。但如果字符集返回为typeNone
,我会这样做:
soup = BeautifulSoup(html)
if encodeType == None:
try:
encodeType = soup.findAll('meta', {'http-equiv':lambda v:v.lower()=='content-type'})
except AttributeError, e:
print e
try:
encodeType = soup.findAll('meta', {'charset':lambda v:v.lower() != None})
except AttributeError, e:
print e
if encodeType == '':
encodeType = 'iso-8859-1'
我正在测试的页面标题中有以下内容:
我希望第一个try语句返回一个空字符串,但我在两个try语句上都遇到了这个错误(这就是为什么现在第二个语句是嵌套的):
“NoneType”对象没有属性“lower”
第二个try语句有什么问题?我猜第一个也是不正确的,因为它抛出了一个错误,而不仅仅是返回空白
或者更好的方法是是否有更优雅的方法从页面中删除任何特殊字符编码?我试图实现的最终结果是,我不在乎任何特殊编码的字符。我想删除编码字符并保留原始文本。我可以跳过以上所有步骤吗?告诉BeautifulSoup仅剥离任何已编码的内容吗?在尝试确定页面的字符编码时,我认为应该尝试的顺序是:
)内容类型:text/html;charset=ISO-8859-1
)在尝试确定页面的字符编码时,我认为应该尝试的顺序是:
)内容类型:text/html;charset=ISO-8859-1
)我决定不管美苏吐出什么我都去。然后,当我解析文档中的每个单词时,如果我不能将其转换为字符串,我就忽略它
for word in doc.lower().split():
try:
word = str(word)
word = self.handlePunctuation(word)
if word == False:
continue
except UnicodeEncodeError, e:
#word couldn't be converted to string; most likely encoding garbage we can toss anyways
continue
我决定不管美苏吐出什么我都去。然后,当我解析文档中的每个单词时,如果我不能将其转换为字符串,我就忽略它
for word in doc.lower().split():
try:
word = str(word)
word = self.handlePunctuation(word)
if word == False:
continue
except UnicodeEncodeError, e:
#word couldn't be converted to string; most likely encoding garbage we can toss anyways
continue
是的,但即使在我最初问题的第一个try语句中,我也在尝试你的#1,但它抛出了一个错误。不知道为什么。是的,但即使在我原始问题的first try语句中,我也在尝试你的#1,但它抛出了一个错误。不知道为什么。