bravo my life!

[항해99][Python][.replace()] beautiful soup을 이용한 웹페이지 크롤링 문제 발생 및 해결 본문

Study/항해99

[항해99][Python][.replace()] beautiful soup을 이용한 웹페이지 크롤링 문제 발생 및 해결

losajjang 2022. 2. 19. 22:09
728x90

- 문제점

requests와 beautiful soup을 이용하여 지니뮤직의 웹페이지를 크롤링하던 중 문제가 발생하였다.

크롤링하려는 항목은 순위, 곡명, 가수이다.

15위인 저스틴비버의 peaches가 19금 등급의 곡인데 크롤링시 필요하지 않은 19금이라는 문자열까지 가져오게 된다.

for song in songs:
        number = song.select_one('td.number').text[0:2].strip()
        title = song.select_one('td.info > a.title.ellipsis').text.strip()
        artist = song.select_one('td.info > a.artist.ellipsis').text.strip()
        print(number, title, artist)

파이선에서 위의 코드를 사용하면 아래의 결과물이 프린트된다.

19금 문자열과 공백이 생겨, 내가 원하는 데이터의 크롤링이 되지 않았다.


-해결 방법

.replace()를 사용하였다.

참고로 .replace()는 아래의 코드와 같은 역할을 한다.

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

이것을 이용하여 아래의 코드처럼 작성하여 해결하였다.

for song in songs:
        number = song.select_one('td.number').text[0:2].strip()
        title = song.select_one('td.info > a.title.ellipsis').text.strip()
        m_title=title.replace('19금',' ').strip()
        artist = song.select_one('td.info > a.artist.ellipsis').text.strip()
        print(number, m_title, artist)

출력된 결과물은 다음과 같다.

19금 문자열이 제거된 내가 원하는 것이 출력되었다.