【问题标题】:re.search().TypeError: cannot use a string pattern on a bytes-like objectre.search().TypeError:不能在类似字节的对象上使用字符串模式
【发布时间】:2016-10-09 21:01:08
【问题描述】:
import urllib.request
import re

f = urllib.request.urlopen('http://www.geekynu.cn/')
html = f.read()

title = re.search('<title>(.*?)</title>', html)
print(title)
#print(title.decode('utf-8')) //I had try to solve by this code.

[python 3.5] 当我使用re.search()阅读网页标题时,出现“TypeError: cannot use a string pattern on a bytes-like object”的错误,我该怎么办?谢了!

【问题讨论】:

标签: python python-3.x


【解决方案1】:

re 需要字节模式(而不是字符串)来搜索类似字节的对象。将b 附加到您的搜索模式中,如下所示:b'&lt;title&gt;(.*?)&lt;/title&gt;'

【讨论】:

    【解决方案2】:

    如果你能加html=html.decode('utf-8'),我想就可以了。

    【讨论】:

    • 当需要在字符串和文件(类似字节的对象)上使用相同的正则表达式时,与接受的答案相比,此答案特别有用。
    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    相关资源
    最近更新 更多