我正在尝试学习如何自动从页面获取网址。在下面的代码中,我试图获取网页的标题:
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)
我收到这个意外错误:
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
我究竟做错了什么?
您想使用以下命令将 html (类似字节的对象)转换为字符串.decode
, e.g. html = response.read().decode('utf-8')
.
See 将字节转换为 Python 字符串 https://stackoverflow.com/questions/606191/convert-bytes-to-a-python-string
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)