sourcetip

유형 오류: re.findall()의 바이트와 같은 개체에 문자열 패턴을 사용할 수 없습니다.

fileupload 2023. 5. 13. 10:42
반응형

유형 오류: re.findall()의 바이트와 같은 개체에 문자열 패턴을 사용할 수 없습니다.

페이지에서 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()

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,예.html = response.read().decode('utf-8').

바이트를 Python 문자열로 변환을 참조하십시오.

문제는 당신의 정규식이 문자열이라는 것입니다.htmlis 바이트:

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

python은 바이트가 어떻게 인코딩되는지 모르기 때문에 문자열 정규식을 사용하려고 하면 예외가 발생합니다.

문자열에 대한 바이트 수는 다음과 같습니다.

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)

자세한 내용은 설명서를 참조하십시오.

마지막 하나를 기준으로, 이것은 pdf 읽기가 완료되었을 때 간단하게 수행할 수 있었습니다.

text = text.decode('ISO-8859-1') 

@아란페이 감사합니다.

언급URL : https://stackoverflow.com/questions/31019854/typeerror-cant-use-a-string-pattern-on-a-bytes-like-object-in-re-findall

반응형