正则表达式上的 Python 类型错误 [英] Python TypeError on regex
本文介绍了正则表达式上的 Python 类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,我有这个代码:
url = 'http://google.com'
linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>')
m = urllib.request.urlopen(url)
msg = m.read()
links = linkregex.findall(msg)
但是python返回这个错误:
But then python returns this error:
links = linkregex.findall(msg)
TypeError: can't use a string pattern on a bytes-like object
我做错了什么?
推荐答案
TypeError: 不能使用字符串模式
在类似字节的对象上
我做错了什么??
您在字节对象上使用了字符串模式.改用字节模式:
You used a string pattern on a bytes object. Use a bytes pattern instead:
linkregex = re.compile(b'<a\s*href=[\'|"](.*?)[\'"].*?>')
^
Add the b there, it makes it into a bytes object
(ps:
>>> from disclaimer include dont_use_regexp_on_html
"Use BeautifulSoup or lxml instead."
)
这篇关于正则表达式上的 Python 类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文