inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

파이썬 입문 및 웹 크롤링을 활용한 다양한 자동화 어플리케이션 제작하기

BeautifulSoup 사용법 및 간단 웹 파싱 실습(2) - 네이버, 인프런

숙제 관련 질문입니다.

186

명한민

작성한 질문수 7

0

숙제를 할때 recommand = soup.select("ul.slides")[ ?? ] ??이 부분을 0 ,1,2 로 나누어서 하면 될것같은데 위 질문드리신 님처럼 저도 똑같은 에러가 납니다. 밑의 댓글을 확인해 보았을 때 이미지 확장자가 gif인것도 있고 다른 것도 있기 때문에 생길 수 도 있다는데 도저히 제 힘으론 해결이 안되는 것 같습니다. 혹 어떠한 것 때문에 알 수 있는지요.

제코드는

from bs4 import BeautifulSoup

import urllib.request as req

import urllib.parse as rep

import os

import sys

import io

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')

sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')

savePath ="C:\imagedown2\"

base = "https://www.inflearn.com/"

quote = rep.quote_plus("추천-강좌")

url = base + quote

res = req.urlopen(url).read()

soup = BeautifulSoup(res,"html.parser")

recommand = soup.select("ul.slides")[2]

print(recommand)

try:

if not(os.path.isdir(savePath)):

os.makedirs(os.path.join(savePath))

except OSError as e:

if e.errno != errno.EEXIST:

print("Failed to create directory!!!!!")

raise

test =[]

en_test=[]

for i,e in enumerate(recommand,1):

open앞 파일 경로 + "파일의 이름", "어떠한 형식으로 작성할것인지"

with open(savePath+"title_"+str(i)+".txt", "wt") as f:

f.write(e.select_one("h4.block_title > a ").string)

fullfilename = os.path.join(savePath, savePath+'img_'+str(i)+'.png')

#urlretrieve 기능은 앞에 파일원본, 파일이 들어갈 경로

test=e.select_one("div.block_media > a > img")['src']

#en_test = test.encode('utf-8')

#req.urlretrieve(en_test,fullfilename)

req.urlretrieve(e.select_one("div.block_media > a > img")['src'],fullfilename)

print("강좌 정보 텍스트 출력 및 이미지 다운 완료!")

이렇게 작성이 되었구요. 에러 코드는

Traceback (most recent call last):

File "C:section2inflearn_homework_img.py", line 38, in

req.urlretrieve(e.select_one("div.block_media > a > img")['src'],fullfilename)

File "C:UsersuserAnaconda3envssection2liburllibrequest.py", line 188, in urlretrieve

with contextlib.closing(urlopen(url, data)) as fp:

File "C:UsersuserAnaconda3envssection2liburllibrequest.py", line 163, in urlopen

return opener.open(url, data, timeout)

File "C:UsersuserAnaconda3envssection2liburllibrequest.py", line 466, in open

response = self._open(req, data)

File "C:UsersuserAnaconda3envssection2liburllibrequest.py", line 484, in _open

'_open', req)

File "C:UsersuserAnaconda3envssection2liburllibrequest.py", line 444, in _call_chain

result = func(*args)

File "C:UsersuserAnaconda3envssection2liburllibrequest.py", line 1297, in https_open

context=self._context, check_hostname=self._check_hostname)

File "C:UsersuserAnaconda3envssection2liburllibrequest.py", line 1254, in do_open

h.request(req.get_method(), req.selector, req.data, headers)

File "C:UsersuserAnaconda3envssection2libhttpclient.py", line 1107, in request

self._send_request(method, url, body, headers)

File "C:UsersuserAnaconda3envssection2libhttpclient.py", line 1142, in _send_request

self.putrequest(method, url, **skips)

File "C:UsersuserAnaconda3envssection2libhttpclient.py", line 984, in putrequest

self._output(request.encode('ascii'))

UnicodeEncodeError: 'ascii' codec can't encode characters in position 24-29: ordinal not in range(128)

[Finished in 10.976s]

이렇게 뜹니다.

python 웹-크롤링

답변 1

0

좋은사람

안녕하세요.
콘솔내용을 보시면 인코딩 에러입니다.
f.read().decode('utf-8') 이런 형식으로 utf-8로 인코딩 하셔야 될 것같습니다.
숙제 같은 경우는 소스코드상에는 에러는 없습니다. 다만, 인프런의 강좌가 계속 바뀌고 이미지 타입도
변하기 때문에 우선은 텍스트 부분만 긁어오는 테스트로 시도하시고 나머지는 섹션을 넘어가서 좀 더 숙련도가
높아진 후 다른 사이트를 대상으로 시도하시면 될 것같습니다.
아래 구글 url을 참고하시기 바랍니다.
https://www.google.com/search?q=UnicodeEncodeError%3A+%E2%80%98ascii%E2%80%99+codec+can%E2%80%99t+encode+characters&oq=UnicodeEncodeError%3A+%E2%80%98ascii%E2%80%99+codec+can%E2%80%99t+encode+characters&aqs=chrome..69i57j69i58.342j0j8&sourceid=chrome&ie=UTF-8

현재 예제에서 error 발생

0

367

3

유튜브 동영상 다운로드

0

1448

2

Atom 에디터 관련

0

337

1

위시켓 폼데이터

0

274

1

스케줄러 사용 관련 질문 드립니다

0

627

1

selenium 에러

0

428

1

Progress bar 쓰레드 관련

0

489

1

Install Package 관련 문의

0

328

1

tkinter 샘플 코드 실행 오류 건

0

1267

1

4-7-6 네이버 & 카카오 주식 정보 가져오기

0

381

1

네이버자동로그인_by_selenium

0

876

1

위시캣 로그인 처리 및 크롤링 질문

0

345

1

2-8-1 네이버이미지 크롤링 질문

1

604

3

li:nth-of-type 질문

0

350

2

에러가 뜨는데 잘 모르겠어요ㅠ

0

401

2

Install Packages 항목이 안보이는 이유가 뭘까요?

0

401

2

환경변수 Path 설정 방법

0

631

1

웹 브라우저 없는 스크랩핑 및 파싱 실습(1) - 인프런

0

333

1

웹 브라우저 없는 스크랩핑 및 파싱 실습(1) -git주소

0

477

3

download2-8-1. py질문

0

203

1

ip 차단 당하는 거 같은데 아무리 랜덤주고, sleep 줘도 안 되는데 다른 방법 더 있을까요??

0

645

1

인프런 환경이 바뀌어서 제나름대로 하는데

0

196

1

다시올려주신 예제파일로하는데

0

190

1

아직도 에러가뜨나보네요?

0

584

1