TypeError : re.findall ()의 바이트 열류 객체에 문자열 패턴을 사용할 수 없습니다.


107

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

내가 뭘 잘못하고 있죠?


답변:



28

문제는 당신의 정규식이 문자열이지만,이다 html바이트 :

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

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

decode바이트를 문자열로 지정할 수 있습니다 .

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)

참조 urlopen 설명서 를 참조하십시오.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.