본문 바로가기
● 크롤링, 자동화/BeautifulSoup

[나도코딩] 파이썬 코딩 무료 강의 (활용편3) - 웹 크롤링? 웹 스크래핑! 4. find_all, for 문

by 0ver-grow 2020. 8. 29.
반응형

활용 1-1 네이버 웹툰 전체목록 가져오기

import requests
from bs4 import BeautifulSoup
url = "https://comic.naver.com/webtoon/weekday.nhn"
res = requests.get(url)
res.raise_for_status()
soup = BeautifulSoup(res.text, "lxml")

class : "title"인 모든 엘리먼트를 찾자

# class : "title"인 모든 엘리먼트를 찾자
# find는 그 조건에 해당되는 첫번째 엘리먼트만 찾음
# find_all은 조건에 해당되는 모든 엘리먼트 찾음
cartoons = soup.find_all("a",attrs={"class":"title"})
for cartoon in cartoons : 
    print(cartoon.get_text())

활용 1-1 가우스 전자 목록 가져오기

import requests
from bs4 import BeautifulSoup
url = "https://comic.naver.com/webtoon/list.nhn?titleId=675554"
res = requests.get(url)
res.raise_for_status()
soup = BeautifulSoup(res.text, "lxml")

이 페이지의 경우 "class" : "title" 이 td 태그에 있다.

gauss = soup.find_all("td",attrs={"class":"title"})
for gaus in gauss :
    print(gaus.get_text())

후기 + 10년 후 가우스

시즌4 430화 내일 봐요

시즌4 429화 잠행

.

.

.

 

첫번째 title과 함께 link를 출력시켜보자

# 첫번째 td태그 밑의 a태그의 text만 가져오자
gauss = soup.find_all("td",attrs={"class":"title"})
title = gauss[0].a.get_text()

# 각화별로 링크를 연결하자. 링크는 a태그의 href속성에 있다.
# 속성을 가져오려면 대괄호 사용할 것
link = gauss[0].a["href"]
print(title)

# link만 출력하면 /webtoon/detail.nhn?titleId=675554&no=911&weekday=mon
# 고로 "https://comic.naver.com"을 붙여줘야 정상 링크
print("https://comic.naver.com"+link)

 

전체 title과 함께 link를 출력시키자

실패

# 첫번째 td태그 밑의 a태그의 text만 가져오자
gauss = soup.find_all("td",attrs={"class":"title"})
for num in len(gauss) :
    title = gauss[num].a.get_text()
    link = gauss[num].a["href"]
    print(title)
    print("https://comic.naver.com"+link)

TypeError Traceback (most recent call last)

<ipython-input-22-d932e7f0825f> in <module>

1 # 첫번째 td태그 밑의 a태그의 text만 가져오자

2 gauss = soup.find_all("td",attrs={"class":"title"})

----> 3 for num in len(gauss) :

4 title = gauss[num].a.get_text()

5 link = gauss[num].a["href"]

TypeError: 'int' object is not iterable

 

해결책 :

An “'int' object is not iterable” error is raised when you try to iterate over an integer value. To solve this error, make sure that you are iterating over an iterable rather than a number.

 

The error is that here, you need to use i to iterate through a list, but you specified an integer, namely len(sequence), instead of the necessary list …for i in len(sequence):

여기서 오류는 목록을 반복하려면 i를 사용해야하지만 len (sequence)의 i에 필요한 목록 대신 정수, 즉 len (sequence)를 지정했습니다.

To iterate through all integers from 0 up to, but not including len(sequence), you can specify the needed list, as follows …

0부터 len (시퀀스)까지 포함하지 않는 모든 정수를 반복하려면 다음과 같이 필요한 목록을 지정할 수 있습니다.

for i in range(len(sequence)):

 

성공

# type(gauss) : class 'bs4.element.ResultSet'
gauss = soup.find_all("td",attrs={"class":"title"})

for i in range(len(gauss)) :
    title = gauss[i].a.get_text()
    link = gauss[i].a["href"]
    print(title)
    print("https://comic.naver.com"+link)

후기 + 10년 후 가우스

시즌4 430화 내일 봐요

시즌4 429화 잠행

 

다른방식1

gauss_all = soup.find_all("td",attrs={"class":"title"})
for gauss in gauss_all : 
    title = gauss.a.get_text()
    link = gauss.a["href"]
    print(title)
    print("https://comic.naver.com"+link)

후기 + 10년 후 가우스

시즌4 430화 내일 봐요

시즌4 429화 잠행

.

.

.

 

다른방식2

# 나도 코딩 방식2
gauss_all = soup.find_all("td",attrs={"class":"title"})
for gauss in gauss_all : 
    title = gauss.a.get_text()
    link = "https://comic.naver.com" + gauss.a["href"]
    print(title, link)

후기 + 10년 후 가우스

시즌4 430화 내일 봐요

시즌4 429화 잠행

.

.

.

 

반응형