gpt4 book ai didi

python - 类型错误 : can't use a string pattern on a bytes-like object in re. findall()

转载 作者:IT老高 更新时间:2023-10-28 21:12:06 25 4
gpt4 key购买 nike

我正在尝试学习如何从页面中自动获取网址。在以下代码中,我试图获取网页的标题:

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

我做错了什么?

最佳答案

您想使用 .decode 将 html(类似字节的对象)转换为字符串,例如html = response.read().decode('utf-8')

Convert bytes to a Python String

关于python - 类型错误 : can't use a string pattern on a bytes-like object in re. findall(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31019854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com