beautifulsou在解析后返回空格文本

2024-05-23 13:47:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在抓取一个本地html文档。然而,当我用BeautifulSoup解析它时,它返回的html格式很难看(如下图所示),这是无法解析的。你知道吗

enter image description here

我使用的简单代码是:

path = 'alerts/myfile.htm'
file = open(os.path.abspath(path))
parser = BeautifulSoup(file,'html.parser')
file.close()

这东西快把我逼疯了。你有过同样的问题吗? 谢谢


Tags: path代码文档parsercloseoshtml格式
3条回答

看起来原始文件是UTF-16格式的。你知道吗

无论出于何种原因,BeautifulSoup(..., from_encoding='utf-16le')都不理解这种情况,但是您可以通过在将文件传递给BS之前手动读取和解码文件来解决这个问题。你知道吗

下面是我创建一个UTF-16LE的HTML文件的脚本,转储它的内容,尝试将它直接传递到BS4,最后使用上面描述的解决方法。你知道吗

$ echo '<html><div>hello</div></html>' | iconv -f utf-8 -t utf-16le > y.html
$ file y.html
$ xxd y.html
00000000: 3c00 6800 7400 6d00 6c00 3e00 3c00 6400  <.h.t.m.l.>.<.d.
00000010: 6900 7600 3e00 6800 6500 6c00 6c00 6f00  i.v.>.h.e.l.l.o.
00000020: 3c00 2f00 6400 6900 7600 3e00 3c00 2f00  <./.d.i.v.>.<./.
00000030: 6800 7400 6d00 6c00 3e00 0a00            h.t.m.l.>...
$ python
>>> import bs4
>>> s = bs4.BeautifulSoup(open('y.html'))
&lt;html&gt;&lt;div&gt;hello&lt;/div&gt;&lt;/html&gt;
>>> s = bs4.BeautifulSoup(open('y.html'), from_encoding='utf-16le')
&lt;html&gt;&lt;div&gt;hello&lt;/div&gt;&lt;/html&gt;
>>> s = bs4.BeautifulSoup(open('y.html'), 'html.parser', from_encoding='utf-16le')
&lt;html&gt;&lt;div&gt;hello&lt;/div&gt;&lt;/html&gt;
>>> d = open('y.html', 'rb').read().decode('utf-16le')
>>> d
'<html><div>hello</div></html>\n'
>>> s = bs4.BeautifulSoup(d)
>>> s
<html><div>hello</div></html>
>>>

在我看来,这是一个关于源文件编码的问题。你知道吗

加载文档时,BeautifulSoup使用名为Unicode Dammit的子库将其转换为UTF-8格式。你知道吗

可能是您的文件已使用不同的编码保存,并且在转换过程中发生了某种错误。你知道吗

由于我手头没有您的html,我可以建议您调查您的文件是ASCII还是Unicode或任何其他编码,然后用以下代码解析文件:

encoding = <your encoding here> (example "iso-8859-8")
parser = BeautifulSoup(file,'html.parser', from_encoding=encoding)

其他编码选项可以找到here

敬礼

更新

同时尝试:

parser = BeautifulSoup(file,'html.parser', from_encoding='utf-8')

我想我解决了:我的文件是用UCL-2编码的。我所做的是:

 path = 'alerts/myfile.htm'
file = open(os.path.abspath(path),'rb')
parser = BeautifulSoup(file.read().decode('utf-8'),'html.parser')
file.close()
parser.find('table', attrs = {'class':'MsoNormalTable'})

下面是输出:

enter image description here

相关问题 更多 >