【发布时间】:2016-02-06 23:58:54
【问题描述】:
我正在使用 Python 3.5 和 Anaconda 2.4.0,并尝试使用 urllib 和 BeautifulSoup 解析站点。我写了一个简单的代码,但它显示了错误的西里尔符号编码(windows-1251 编码中的 html 页面),所以显示如下:
[<td align="center" widh="30"><a href="/registration/"><img alt="\xd0\xa0\xd0\xb5\xd0\xb3\xd0\xb8\xd1\x81\xd1\x82\xd1\x80\xd0\xb0\xd1\x86\xd0\xb8\xd1\x8f" border="0" src="/images/pers.png"/></a></td>]等
我尝试了很多方法来对此进行编码,但都失败了。你能帮帮我吗?
提前致谢。
import urllib.request
from bs4 import BeautifulSoup
def get_html(url):
response = urllib.request.urlopen(url)
return response.read()
def parse(html):
soup = BeautifulSoup(html, 'lxml')
table = soup.find('table')
for row in table.find_all('tr')[1:]:
cols=row.find_all('td')
print(str(cols).encode('utf-8'))
def main():
parse(get_html('http://www.prof-volos.ru/hair/shampoo/damaged/sale/1/'))
if __name__ == '__main__':
main()
【问题讨论】:
-
看看下面的答案是否适合你。
-
显示错误 [解码错误 - 输出不是 utf-8]
-
您是否使用了下面的确切代码?你能粘贴完整的错误吗?您使用的是什么操作系统?
-
是的。 [解码错误 - 输出非 utf-8] [解码错误 - 输出非 utf-8] [0.9s 完成],Win7
-
有趣——我的 python2.7 版本在 OS X 上运行,而 Python3 版本在 Linux 上运行。我会看看能不能找到一个 Windows 盒子。您是否有一台 Linux 机器可以用来查看它是否可以让您的脚本运行?
标签: python parsing beautifulsoup urllib anaconda