相关疑难解决方法(0)

在Python中获取HTTP响应的字符集/编码的好方法

寻找一种使用Python urllib2或任何其他Python库获取HTTP响应的字符集/编码信息的简单方法.

>>> url = 'http://some.url.value'
>>> request = urllib2.Request(url)
>>> conn = urllib2.urlopen(request)
>>> response_encoding = ?
Run Code Online (Sandbox Code Playgroud)

我知道它有时出现在'Content-Type'标题中,但该标题有其他信息,并且它嵌入在我需要解析的字符串中.例如,Google返回的Content-Type标头是

>>> conn.headers.getheader('content-type')
'text/html; charset=utf-8'
Run Code Online (Sandbox Code Playgroud)

我可以使用它,但我不确定格式的一致性.我很确定charset可能完全丢失,所以我必须处理这个边缘情况.某种类型的字符串拆分操作使得"utf-8"从中看出来似乎是做错这种事情的错误方法.

>>> content_type_header = conn.headers.getheader('content-type')
>>> if '=' in content_type_header:
>>>  charset = content_type_header.split('=')[1]
Run Code Online (Sandbox Code Playgroud)

这种代码感觉就像做了太多的工作.我也不确定它是否适用于所有情况.有没有人有更好的方法来做到这一点?

python urllib2 httprequest character-encoding

26
推荐指数
3
解决办法
4万
查看次数

对字符串python的Httpresponse

我正在尝试显示一个网页,但由于它不会将对象视为字符串,因此无法正确显示换行符(显示\n)。我怎样才能正确地使结果成为一个字符串,因为这似乎不起作用。谢谢!

result = urllib.request.urlopen(requesturl).read()
return str(result)
Run Code Online (Sandbox Code Playgroud)

python string httpresponse python-3.5

3
推荐指数
1
解决办法
1万
查看次数