类型错误:不能在 re.findall() 中的类似字节的对象上使用字符串模式 [英] TypeError: can't use a string pattern on a bytes-like object in re.findall()

查看:61
本文介绍了类型错误:不能在 re.findall() 中的类似字节的对象上使用字符串模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to learn how to automatically fetch urls from a page. In the following code I am trying to get the title of the webpage:

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)

我收到了这个意外错误:

And I get this unexpected error:

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').

You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8').

参见将字节转换为 Python 字符串

这篇关于类型错误:不能在 re.findall() 中的类似字节的对象上使用字符串模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆