Python 类型错误:can';t在re.findall()中的类似字节的对象上使用字符串模式
我正在尝试学习如何从页面自动获取URL。在以下代码中,我尝试获取网页的标题:Python 类型错误:can';t在re.findall()中的类似字节的对象上使用字符串模式,python,python-3.x,web-crawler,Python,Python 3.x,Web Crawler,我正在尝试学习如何从页面自动获取URL。在以下代码中,我尝试获取网页的标题: import urllib.request import re url = "http://www.google.com" regex = r'<title>(,+?)</title>' pattern = re.compile(regex) with urllib.request.urlopen(url) as response: html = response.read() t
import urllib.request
import re
url = "http://www.google.com"
regex = r'<title>(,+?)</title>'
pattern = re.compile(regex)
with urllib.request.urlopen(url) as response:
html = response.read()
title = re.findall(pattern, html)
print(title)
导入urllib.request
进口稀土
url=”http://www.google.com"
正则表达式=r'(,+?)'
pattern=re.compile(regex)
使用urllib.request.urlopen(url)作为响应:
html=response.read()
title=re.findall(模式,html)
印刷品(标题)
我得到了一个意想不到的错误:
Traceback (most recent call last):
File "path\to\file\Crawler.py", line 11, in <module>
title = re.findall(pattern, html)
File "C:\Python33\lib\re.py", line 201, in findall
return _compile(pattern, flags).findall(string)
TypeError: can't use a string pattern on a bytes-like object
回溯(最近一次呼叫最后一次):
文件“path\to\File\Crawler.py”,第11行,在
title=re.findall(模式,html)
文件“C:\Python33\lib\re.py”,第201行,findall中
返回编译(模式、标志).findall(字符串)
TypeError:无法在类似字节的对象上使用字符串模式
我做错了什么?您想使用.decode
将html(类似字节的对象)转换为字符串,例如html=response.read().decode('utf-8')
请参见问题在于您的正则表达式是一个字符串,而
html
是:
或使用字节正则表达式:
regex = rb'<title>(,+?)</title>'
# ^
有关更多详细信息,请参阅。此错误的可能重复解决了错误
TypeError:无法在类似字节的对象上使用字符串模式
,但随后出现了类似UnicodeDecodeError的错误:“utf-8”编解码器无法解码位置1中的字节0xb2:无效的起始字节
。我通过使用.decode(“utf-8”,“忽略”)
:“忽略”忽略修复了它。如果这是你想要的,那么一切都好。然而,有时这类问题掩盖了一个更深层次的问题,例如,你想要解码的东西实际上是不可解码的或不应该是可解码的,例如,压缩或加密的文本。或者它可能需要一些其他编码,比如utf-16
。警告买主。
html = html.decode('ISO-8859-1') # encoding may vary!
title = re.findall(pattern, html) # no more error
regex = rb'<title>(,+?)</title>'
# ^
with urllib.request.urlopen(url) as response:
encoding = response.info().get_param('charset', 'utf8')
html = response.read().decode(encoding)