如何处理来自 urllib.request.urlopen() 的响应编码,以避免 TypeError: can't use a string pattern on a bytes-like object
我尝试使用 urllib.request.urlopen() 打开网页,然后使用正则表达式搜索它,但这会出现以下错误:
类型错误:无法在类似字节的对象上使用字符串模式
我明白为什么,urllib.request.urlopen()
返回一个字节流,所以re
不知道要使用的编码。在这种情况下我该怎么办?有没有办法在 urlrequest 中指定编码方法,或者我需要自己重新编码字符串?如果是这样,我想做什么,我假设我应该从标头信息或编码类型(如果在 html 中指定)读取编码,然后将其重新编码为该编码?
I'm trying to open a webpage using urllib.request.urlopen()
then search it with regular expressions, but that gives the following error:
TypeError: can't use a string pattern on a bytes-like object
I understand why, urllib.request.urlopen()
returns a bytestream, so re
doesn't know the encoding to use. What am I supposed to do in this situation? Is there a way to specify the encoding method in a urlrequest maybe or will I need to re-encode the string myself? If so what am I looking to do, I assume I should read the encoding from the header info or the encoding type if specified in the html and then re-encode it to that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
对于我来说,解决方案如下(python3):
As for me, the solution is as following (python3):
您只需要使用
Content-Type
标头(通常是最后一个值)来解码响应。 教程中也给出了一个示例。You just need to decode the response, using the
Content-Type
header typically the last value. There is an example given in the tutorial too.最近两天我也遇到了同样的问题。我终于有解决办法了。
我正在使用
urlopen()
返回的对象的info()
方法:I had the same issues for the last two days. I finally have a solution.
I'm using the
info()
method of the object returned byurlopen()
:这是一个简单的 http 请求示例(我测试过并且有效)...
请务必阅读文档。
如果你想做一些更详细的GET/POST REQUEST。
Here is an example simple http request (that I tested and works)...
Make sure to read the documentation.
If you want to do something more detailed GET/POST REQUEST.
对于请求:
With requests:
将输出如下内容:
text/html;字符集=utf-8
Will output something like this:
text/html; charset=utf-8
发出请求后
req = urllib.request.urlopen(...)
您必须通过调用html_string = req.read()
来读取请求,这将为您提供然后您可以按照您想要的方式解析字符串响应。after you make a request
req = urllib.request.urlopen(...)
you have to read the request by callinghtml_string = req.read()
that will give you the string response that you can then parse the way you want.