Programming/Python 웹 스크래퍼 만들기

Python BeautifulSoup

2022. 11. 17. 21:00

5.4 BeautifulSoup

 

아래 코드로 weworkremotely 웹사이트의 python 구인정보를 가져왔다.

from requests import get

base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="

search_term = "python"

response = get(f'{base_url}{search_term}')
if response.status_code != 200:
    print("Can't request website")
else:
    print(response.text)

jobs 라는 class 를 가진 section 을 찾아 추출한다.

그리고 section 에 있는 ul 안에서 모든 li 를 찾는다.

많은 텍스트 안의 내용을 검색하기 위해 beautifulsoup 를 사용한다.

beautifulsoup 는 여러 method 들을 제공하는데

예를 들면 find_all 이라는 메서드가 있다.

사용자가 가진 document 에서 HTML 태그를 찾을 수 있게 해준다.

ex) soup.find_all("title")을 하면 title 이라는 HTML 태그를 가져온다.

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all

 

Beautiful Soup Documentation — Beautiful Soup 4.9.0 documentation

Non-pretty printing If you just want a string, with no fancy formatting, you can call str() on a BeautifulSoup object, or on a Tag within it: str(soup) # ' I linked to example.com ' str(soup.a) # ' I linked to example.com ' The str() function returns a str

www.crummy.com

 

아래 코드로 beautifulsoup 를 사용한다.

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

html을 첫번째 argument로 전해주고 'html.parser'라는 문자열을 전해준다.

이건 사용자가 beautifulsoup 한테 html을 보내준다고 하는것과 같다.

 

이제 실제코드에 적용을 해서 나만의 soup를 만든다.

response 는 base_url + search_term 이 합쳐진 변수로 검색해서 나온 결과를 웹사이트로 보여준다.

get이라는 메서드로 그 웹사이트 검색 결과(HTML 코드들)를 response 라는 변수에 넣어

status_code(http 상태코드) 가 정상 접속이 아니면 Can't request webisite 라는 문구를 출력하고

status_code(http 상태코드) 가 정상이면 response 변수값을 text 형태로 출력하게 만들었다.

beautifulsoup 를 활용하여  

soup = BeautifulSoup(html_doc, 'html.parser')          → 예시

soup = BeautifulSoup(response.text,'html.parser')    → 실제 적용 코드

soup의 find_all 메서드를 사용해서 title 이라는 HTML 태그를 찾아서 출력했다.

from requests import get
from bs4 import BeautifulSoup

base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="

search_term = "python"

response = get(f'{base_url}{search_term}')
if response.status_code != 200:
    print("Can't request website")
else:
    soup = BeautifulSoup(response.text,'html.parser')
    print(soup.find_all('title'))

출력값:

[<title>We Work Remotely: Advanced Remote Job Search</title>]

 

 

이제 실제로 찾을 타겟인 jobs라는 class를 가진 section 을 출력해본다.

from requests import get
from bs4 import BeautifulSoup

base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="

search_term = "python"

response = get(f'{base_url}{search_term}')
if response.status_code != 200:
    print("Can't request website")
else:
    soup = BeautifulSoup(response.text,'html.parser')
    print(soup.find_all('section',class_="jobs"))

출력값:

 

검색한 웹사이트와 동일하게 가져왔는지 확인하기 위해

실제 웹사이트상의 맨 위의 구직 회사와 코드상의 회사 이름이 같은지 확인해본다.

위와 같이 일 정보가 있는 section 을 가져왔다.

이 결과물을 jobs 변수에 넣어둔다.

from requests import get
from bs4 import BeautifulSoup

base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="

search_term = "python"

response = get(f'{base_url}{search_term}')
if response.status_code != 200:
    print("Can't request website")
else:
    soup = BeautifulSoup(response.text,'html.parser')
    jobs = print(soup.find_all('section',class_="jobs"))

 

'Programming > Python 웹 스크래퍼 만들기' 카테고리의 다른 글

Python Job Posts  (1) 2022.11.21
Python Keyword Arguments  (0) 2022.11.18
Python WebScrapper Introduction  (1) 2022.11.16
Python Requests, Get 복습  (2) 2022.11.15
Python Requests  (0) 2022.11.14
'Programming/Python 웹 스크래퍼 만들기' 카테고리의 다른 글
  • Python Job Posts
  • Python Keyword Arguments
  • Python WebScrapper Introduction
  • Python Requests, Get 복습
Security Engineer
Security Engineer
IT 공부
Security Engineer
IT-log
Security Engineer
전체
오늘
어제
  • 분류 전체보기 (177)
    • Programming (39)
      • Python 웹 스크래퍼 만들기 (39)
    • IT 지식 (70)
      • IT 정보 (28)
      • CS 기초 (24)
      • 운영체제 (8)
      • IT 인프라 기초 (10)
    • 보안 (45)
      • 악성코드 분석 (10)
      • Bandit 워게임 (25)
      • 취미로 해킹 2 (6)
      • 환경 구축 (4)
    • 웹 해킹 (23)
      • 웹 기초 지식 (8)
      • SQL 기본 (2)
      • 웹 해킹 및 시큐어 코딩 기초 (13)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 리눅스
  • Selenium
  • 모의해킹
  • 취미로 해킹
  • 파이썬
  • CSS
  • it 운영
  • 시큐어 코딩
  • bandit
  • flask
  • webScrapper
  • Web
  • 컴퓨터
  • Python
  • 웹 개발
  • IT 인프라
  • HTML
  • Def
  • 워게임
  • CS
  • CS 기초
  • Beautifulsoup
  • 웹 해킹
  • 악성코드 분석
  • 해킹
  • 운영체제
  • WarGame
  • overthewire
  • 취미로해킹
  • 악성코드

최근 댓글

최근 글

hELLO · Designed By 정상우.
Security Engineer
Python BeautifulSoup
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.