close

[Solved] Type: can’t use a string pattern on a bytes-like object in re.findall()

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Type: can’t use a string pattern on a bytes-like object in re.findall() in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Type: can’t use a string pattern on a bytes-like object in re.findall() Error Occurs?

Today I get the following error Type: can’t use a string pattern on a bytes-like object in re.findall() in python.

How To Solve Type: can’t use a string pattern on a bytes-like object in re.findall() Error ?

  1. How To Solve Type: can't use a string pattern on a bytes-like object in re.findall() Error ?

    To Solve Type: can't use a string pattern on a bytes-like object in re.findall() Error You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8').

  2. Type: can't use a string pattern on a bytes-like object in re.findall()

    To Solve Type: can't use a string pattern on a bytes-like object in re.findall() Error You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8').

Solution 1

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

Solution 2


The problem is that your regex is a string, but html is bytes:

>>> type(html)
<class 'bytes'>

Since python doesn’t know how those bytes are encoded, it throws an exception when you try to use a string regex on them.

You can either decode the bytes to a string:

html = html.decode('ISO-8859-1')  # encoding may vary!
title = re.findall(pattern, html)  # no more error

Or use a bytes regex:

regex = rb'<title>(,+?)</title>'
#        ^

In this particular context, you can get the encoding from the response headers:

with urllib.request.urlopen(url) as response:
    encoding = response.info().get_param('charset', 'utf8')
    html = response.read().decode(encoding)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read