天天看点

python3 使用urllib.request模块,关于bytes和string的那些事

python 3.4.2 使用urllib.request模块获取网页内容,虽说知道要注意编解码的问题,但有些细节还是不清楚,终于碰到了TypeError的错误:

TypeError:can't use a string pattern on a bytes-like object
           

知道是字节和字符使用错误,但是问题在哪儿呢?只好敲代码问问了。

import urllib.request

url = 'http://www.baidu.com'
req = urllib.request.Request(url)
response = req.urlopen(req)
page = response.read()
the_page = page.decode("UTF-8")
b_page = the_page.encode("UTF-8")
           

page 的类型是: bytes

the_page 的类型是: string

b_page 的类型是: bytes

知道了这些细节,修改代码bug就很简单了。