正则表达式上的Python TypeError

kam*_*lot 51 python regex typeerror python-3.x

所以,我有这个代码:

url = 'http://google.com'
linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>')
m = urllib.request.urlopen(url)
msg = m.read()
links = linkregex.findall(msg)
Run Code Online (Sandbox Code Playgroud)

但是然后python返回这个错误:

links = linkregex.findall(msg)
TypeError: can't use a string pattern on a bytes-like object
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Len*_*bro 70

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

我做错了什么??

您在字节对象上使用了字符串模式.改为使用字节模式:

linkregex = re.compile(b'<a\s*href=[\'|"](.*?)[\'"].*?>')
                       ^
            Add the b there, it makes it into a bytes object
Run Code Online (Sandbox Code Playgroud)

(PS:

 >>> from disclaimer include dont_use_regexp_on_html
 "Use BeautifulSoup or lxml instead."
Run Code Online (Sandbox Code Playgroud)

)