gpt4 book ai didi

python - utf8编解码器无法在python中解码字节0x96

转载 作者:IT老高 更新时间:2023-10-28 20:21:26 25 4
gpt4 key购买 nike

我正在尝试检查某个单词是否出现在许多网站的页面上。该脚本在 15 个站点上运行良好,然后停止。

UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 15344: invalid start byte

我在 stackoverflow 上进行了搜索,发现了很多问题,但我似乎无法理解我的情况出了什么问题。

我想解决它,或者如果有错误跳过该站点。请建议我如何做到这一点,因为我是新手,下面的代码本身花了我一天的时间来写。顺便说一下,脚本停止的站点是 http://www.homestead.com

filetocheck = open("bloglistforcommenting","r")
resultfile = open("finalfile","w")

for countofsites in filetocheck.readlines():
sitename = countofsites.strip()
htmlfile = urllib.urlopen(sitename)
page = htmlfile.read().decode('utf8')
match = re.search("Enter your name", page)
if match:
print "match found : " + sitename
resultfile.write(sitename+"\n")

else:
print "sorry did not find the pattern " +sitename

print "Finished Operations"

根据 Mark 的评论,我更改了代码以实现 beautifulsoup

htmlfile = urllib.urlopen("http://www.homestead.com")
page = BeautifulSoup((''.join(htmlfile)))
print page.prettify()

现在我收到此错误

page = BeautifulSoup((''.join(htmlfile)))
TypeError: 'module' object is not callable

我正在尝试 http://www.crummy.com/software/BeautifulSoup/documentation.html#Quick%20Start 中的快速入门示例.如果我复制粘贴它,那么代码可以正常工作。

我终于让它工作了。谢谢大家的帮助。这是最终代码。

import urllib
import re
from BeautifulSoup import BeautifulSoup

filetocheck = open("listfile","r")

resultfile = open("finalfile","w")
error ="for errors"

for countofsites in filetocheck.readlines():
sitename = countofsites.strip()
htmlfile = urllib.urlopen(sitename)
page = BeautifulSoup((''.join(htmlfile)))
pagetwo =str(page)
match = re.search("Enter YourName", pagetwo)
if match:
print "match found : " + sitename
resultfile.write(sitename+"\n")

else:
print "sorry did not find the pattern " +sitename

print "Finished Operations"

最佳答案

15344 处的字节为 0x96。大概在位置 15343 有一个字符的单字节编码,或者是多字节编码的最后一个字节,使 15344 成为一个字符的开头。 0x96 是二进制 10010110,任何匹配模式 10XXXXXX(0x80 到 0xBF)的字节只能是 UTF-8 编码中的第二个或后续字节。

因此流不是 UTF-8 或已损坏。

检查您链接到的 URI,我们找到了 header :

Content-Type: text/html

由于没有规定编码,我们应该使用 HTTP 的默认值,即 ISO-8859-1(又名“Latin 1”)。

检查内容我们发现了一行:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

对于由于某种原因无法正确设置其 HTTP 标题的人来说,这是一种后备机制。这次我们被明确告知字符编码是 ISO-8859-1。

因此,没有理由期望将其作为 UTF-8 读取。

不过,为了更有趣,当我们考虑在 ISO-8859-1 0x96 编码 U+0096 时,我们发现 ISO-8859-1 也不正确。似乎创建页面的人对您自己也犯了类似的错误。

从上下文来看,他们似乎实际上使用了 Windows-1252,因为编码 0x96 编码了 U+2013(EN-DASH,看起来像 )。

因此,要解析您要在 Windows-1252 中解码的特定页面。

更一般地说,您希望在选择字符编码时检查 header ,虽然在这种情况下它可能不正确(或者可能不正确,但实际上有多个“ISO-8859-1”编解码器是 Windows-1252),你会更经常是正确的。您仍然需要通过后备阅读来捕捉这样的失败。 decode 方法采用称为 errors 的第二个参数。默认是'strict',但你也可以有'ignore', 'replace', 'xmlcharrefreplace'(不合适),'backslashreplace'(不合适),您可以使用 codecs.register_error() 注册自己的后备处理程序。

关于python - utf8编解码器无法在python中解码字节0x96,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7873556/

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