如何在python中下载具有正确字符集的任何(!)网页? [英] How to download any(!) webpage with correct charset in python?

查看:53
本文介绍了如何在python中下载具有正确字符集的任何(!)网页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 python 抓取网页时,必须知道页面的字符编码.如果字符编码错误,那么您的输出将会一团糟.

When screen-scraping a webpage using python one has to know the character encoding of the page. If you get the character encoding wrong than your output will be messed up.

人们通常使用一些基本的技术来检测编码.他们要么使用标题中的字符集或元标记中定义的字符集,要么使用 编码检测器(不关心元标记或标题).仅使用其中一种技术,有时您将无法获得与在浏览器中相同的结果.

People usually use some rudimentary technique to detect the encoding. They either use the charset from the header or the charset defined in the meta tag or they use an encoding detector (which does not care about meta tags or headers). By using only one these techniques, sometimes you will not get the same result as you would in a browser.

浏览器这样做:

  • 元标记始终优先(或 xml 定义)
  • 当元标记中没有定义字符集时,使用标头中定义的编码
  • 如果根本没有定义编码,那么就该进行编码检测了.

(嗯……至少我相信大多数浏览器都是这样做的.文档真的很稀缺.)

(Well... at least that is the way I believe most browsers do it. Documentation is really scarce.)

我正在寻找一个可以像浏览器那样决定页面字符集的库.我相信我不是第一个需要适当解决方案的人这个问题.

What I'm looking for is a library that can decide the character set of a page the way a browser would. I'm sure I'm not the first who needs a proper solution to this problem.

根据 Beautiful Soup 的文档.

Beautiful Soup 按优先级尝试以下编码,将您的文档转换为 Unicode:

Beautiful Soup tries the following encodings, in order of priority, to turn your document into Unicode:

  • 您传入的编码fromEncoding 参数到汤构造函数.
  • 在文档本身中发现的一种编码:例如,在 XML 声明或(对于 HTML 文档)http-equiv META 标签中.如果 Beautiful Soup 在文档中发现这种编码,它会从头开始重新解析文档并尝试新的编码.唯一的例外是,如果您明确指定了一种编码,并且该编码确实有效:那么它将忽略它在文档中找到的任何编码.
  • 通过查看文件的前几个字节来嗅探的编码.如果检测到编码在这个阶段,它将是其中之一UTF-* 编码、EBCDIC 或 ASCII.
  • 安chardet 嗅探的编码库,如果你安装了它.
  • UTF-8
  • Windows-1252

推荐答案

我会使用 html5lib 为此.

这篇关于如何在python中下载具有正确字符集的任何(!)网页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆