使用BeautifulSoup解析和刮擦编码问题

时间:2016-03-22 23:32:22

标签: html python-3.x encoding web-scraping beautifulsoup

利用Python3,BeautifulSoup和非常小的正则表达式,我试图从这个网页上删除文本:

http://www.presidency.ucsb.edu/ws/?pid=2921

我已成功将其html提取到文件中。事实上,我已经完成了本网站上几乎所有的总统演讲。我在我的计算机上本地保存了247个(可能的258个)演讲'html。

我从每个页面中提取文本的代码如下所示:

import re
from bs4 import BeautifulSoup

with open('scan_here.txt') as reference:       #'scan_here.txt' is a file containing all the pages whose html I have downloaded successfully
    for line in reference:
        line_unclean = reference.readline() #each file's name is just a random string of 5-6 integers
        line = str(re.sub(r'\n', '', line_unclean)) #for removing '\n' from each file name
        f = open(('local_path_to_folder_containing_all_the_html_files\\') + line)
        doc = f.read()
        soup = BeautifulSoup(doc, 'html.parser')
        for speech in soup.select('span.display-text'):
            final_speech = str(speech)
            print(final_speech)

利用此代码,我收到以下错误消息:

Traceback (most recent call last):
  File "extract_individual_speeches.py", line 11, in <module>
    doc = f.read()
  File "/usr/lib/python3.4/codecs.py", line 319, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x97 in position 56443: invalid start byte

我知道这是一个解码错误,并试图在其他html文件上运行此代码,而不仅仅是第一个出现在'scan_text.txt'文件名列表中的代码。同样的错误,所以我认为这是html文件本地的编码问题。

我认为问题可能在于html的第三行,它对我的​​所有html文件都有相同的编码:

<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1251">

什么是'windows-1251?'我认为这是问题所在。我查了一下,看到有一些Windows-1251到UTF-8转换器,但我没有看到一个适用于Python的。

我发现了SO thread which seems to deal with this issue of conversion,但我不确定如何将其与现有代码集成。

非常感谢TIA提供的有关此问题的任何帮助。

1 个答案:

答案 0 :(得分:1)

&#39;窗户-1251&#39;是一种标准的Windows编码。你需要的是UTF-8。您可以在打开文件时定义编码。

尝试这样的事情:

text = text.decode('windows-1251')

或:

import codecs
f = codecs.open(file,'r','windows-1251').read()
codecs.open(file,'w','UTF-8').write(f)

您也可以使用编解码器:

 jQuery(function ($) {
      $("a.edit").fancybox();
 });


<a class="edit" href="showForm.php?id=<?=$row['id']?>"> Edit </a>