gpt4 book ai didi

python - 使用 BeautifulSoup 从 HTML 页面获取内容类型

转载 作者:太空宇宙 更新时间:2023-11-03 19:31:51 25 4
gpt4 key购买 nike

我正在尝试获取我抓取的页面的字符编码,但在某些情况下它会失败。这是我正在做的事情:

resp = urllib2.urlopen(request)
self.COOKIE_JAR.extract_cookies(resp, request)
content = resp.read()
encodeType= resp.headers.getparam('charset')
resp.close()

这是我的第一次尝试。但是如果字符集返回类型为 None ,我这样做:

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'

我正在测试的页面标题中有这样的内容: <meta charset="ISO-8859-1">

我希望第一个 try 语句返回一个空字符串,但是我在两个 try 语句上都收到此错误(这就是现在嵌套第二个语句的原因):

“NoneType”对象没有属性“lower”

第二个 try 语句有什么问题?我猜第一个也是不正确的,因为它抛出了一个错误,而不仅仅是返回空白。

或者更好有没有一种更优雅的方法来从页面中删除任何特殊字符编码?我想要实现的最终结果是我不关心任何特殊编码的字符。我想删除编码字符并保留原始文本。我可以跳过上述所有内容并告诉 BeautifulSoup 只删除任何编码的内容吗?

最佳答案

我决定只接受 BeautifulSoup 吐出的任何内容。然后,当我解析文档中的每个单词时,如果无法将其转换为字符串,我就会忽略它。

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

关于python - 使用 BeautifulSoup 从 HTML 页面获取内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5411279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com