【问题标题】:Requests to Handle Response Encoding [duplicate]处理响应编码的请求[重复]
【发布时间】:2016-09-16 15:50:18
【问题描述】:

我正在使用requests 请求页面。任务很简单,但是编码有问题。该页面包含非ascii,土耳其语字符,但在HTML源中,结果如下:

ÇINARTEPE # What it looks like
ÇINARTEPE # What it is like in HTML source

所以,下面的操作没有返回我预期的结果:

# What I have tried as encoding
req.encoding = "utf-8"
req.encoding = "iso-8859-9"
req.encoding = "iso-8859-1"

# The operations
"ÇINARTEPE" in req.text # False, it must return True
bytes("ÇINARTEPE", "utf-8") in req.content # False
bytes("ÇINARTEPE", "iso-8859-9") in req.content # False
bytes("ÇINARTEPE", "iso-8859-1") in req.content # False

我只想找出 "ÇINARTEPE" 字符串是否在 HTML 源代码中。

更多信息

一个例子:

req = requests.get("http://www.eshot.gov.tr/tr/OtobusumNerede/290")
"ÇINARTEPE" in req.text # False
req.encoding = "iso-8859-1"
"ÇINARTEPE" in req.text # False
req.encoding = "iso-8859-9"
"ÇINARTEPE" in req.text # False
# Supposed to return True

环境

  • python 3.5.1
  • 请求 2.10.0

【问题讨论】:

  • 你是怎么处理的?给我们看一些代码!
  • 更新了问题
  • 不就是html.unescape("ÇINARTEPE")吗? ^checks^ 是的,我想就是这样。
  • @TadhgMcDonald-Jensen,等你写答案标记为有效。
  • JEan PAul 击败了我,我宁愿错过一些代表然后发布重复的答案。

标签: python python-3.x web-scraping python-requests


【解决方案1】:

您需要做的是取消转义 HTML 中的 HTML 代码。 stackoverflow 中已经有一些答案,请查看this post

但基本上一种方法是

from HTMLParser import HTMLParser
parser = HTMLParser()
html_decoded_string = parser.unescape(html_encoded_string)

更新

从 python3 docs 得到了更好的答案并经过测试

>>> import html
>>> html.unescape("ÇINARTEPE")
'ÇINARTEPE'

【讨论】:

  • OP 正在使用“python 3.5.1”,这是 python 2 的模块名称。python 3 等效项是 html.parser
  • 还要注意 unescape 方法只能从 html 模块访问,所以在 python 3 中你真的可以只使用 import html ; html_decoded_string = html.unescape(html_encoded_string)
  • 我刚刚安装并给了我ImportErrormarkupbase 2.x 版本的模块。 @TadhgMcDonald-Jensen 是对的。
  • 奇怪的是html.escape("ÇINARTEPE")并没有改变它,不知道为什么?
  • Tadhg,答案在'ç' in html.entities.codepoint2name,我猜它与 HTML 的标记符号有关,因为它不是其中之一,不需要转义。
猜你喜欢
  • 1970-01-01
  • 2021-12-02
  • 2018-04-12
  • 2010-12-08
  • 2011-02-23
  • 1970-01-01
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多